按固定间隔循环列和平均元素

2024-06-17 10:46:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我完全卡住了。在我的原始数据帧中,我有一列感兴趣的元素(荧光),我希望以固定的间隔(5)获取固定数量的元素(=3,黄色),并对它们进行平均。输出应保存到新列表中

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, 20, 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

欢迎任何意见!! 先谢谢你


Tags: to元素列表数量原始数据间隔timerange
2条回答

这里,我将每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, 14, 43, 87, 53, 81, 98, 34, 33, 60, 82, 86, 6, 81, 96, 99, 10, 76, 73, 63, 89, 70, 29, 32, 3, 98, 52, 37, 8, 2, 80, 50, 99, 71, 5, 7, 35, 56, 47, 40, 2, 8, 56, 69, 15, 76, 52, 24, 56, 89, 52, 30, 70, 68, 71, 17, 4, 39, 39, 85, 29, 18, 71, 92, 8, 1, 95, 52, 94, 71, 88, 59, 64, 100, 96, 65, 15, 89, 19, 63, 38, 50, 65, 52, 26, 46, 79, 85, 32, 12, 67, 35, 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)

相关问题 更多 >