以固定间隔循环遍历列和平均值元素

问题描述

我完全被困住了。在我的原始数据帧中,我有1列感兴趣的列(荧光),并且我想以固定间隔(5)提取固定数量的元素(= 3,黄色)并取其平均值。输出应保存到NewList中。

fluorescence = df.iloc[1:20,0]
fluorescence=pd.to_numeric(fluorescence)
## add a list to count
fluorescence['time']= list(range(1,20,1))
## create a list with interval
interval = list(range(1,5))
NewList=[]

for i in range(len(fluorescence)):
  if fluorescence['time'][i] == interval[i]:
   NewList.append(fluorescence[fluorescence.tail(3).mean()])

print(NewList)

enter image description here

欢迎任何输入!! 预先谢谢你

解决方法

在这里,我每5个连续迭代取一个数据帧子集,并取尾3行均值

import pandas as pd    
fluorescence=pd.DataFrame([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])    


NewList=[]    
j=0    
for i1 in range(4,len(fluorescence),5):    
    NewList.append(fluorescence.loc[j:i1,0].tail(3).mean())    
    j=i1    

print(NewList)   
,

如果您有数据列表,并且想从每5个数据中抓取3个条目,则可以按以下方式细分列表:

from statistics import mean
data = [63,64,43,91,44,84,87,53,81,98,34,33,60,82,86,96,99,76,73,63,89,70,29,32,52,37,80,50,71,35,56,47,40,69,15,24,30,68,17,39,85,18,92,1,95,94,88,59,100,65,19,38,26,46,79,67,22,54,81]
new_data = []
for i in range(0,len(data),5):
    every_five = data[i:i+5]
    three_out_of_five = every_five[2:5]
    new_data.append(mean(three_out_of_five))
print(new_data)