Search code examples
pythonloopspandas-groupbymeanintervals

loop over column and average elements at fixed interval


I am completely stuck. In my original dataframe I have 1 column of interest (fluorescence) and I want to take a fixed amount of elements (=3, color yellow) at fixed interval (5) and average them. The output should be saved into a 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)

enter image description here

Any input is welcome!! Thank you in advance


Solution

  • Here, I'm taking subset of dataframe for every 5 consecutive iterations and taking tail 3 rows mean

    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)