【问题标题】:loop over column and average elements at fixed interval以固定间隔循环列和平均元素
【发布时间】:2021-02-06 15:49:42
【问题描述】:

我完全被困住了。在我的原始数据框中,我有 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, 20, 5))
NewList=[]

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

print(NewList)

欢迎任何意见! 提前谢谢你

【问题讨论】:

    标签: python loops pandas-groupby mean intervals


    【解决方案1】:

    在这里,我每 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)   
    

    【讨论】:

      【解决方案2】:

      如果您有一个数据列表,并且想要从每 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)
      

      【讨论】:

      • 非常感谢!代码无效,我理解!
      • @MartinaLazzarin 很高兴!
      猜你喜欢
      • 2020-05-15
      • 2019-11-10
      • 2015-04-14
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 2016-08-28
      相关资源
      最近更新 更多