简体   繁体   中英

backwards average only when value in column changes

I tried to calculate the average for the last x rows in a DataFrame only when the value is changing

A and B are my inputs and C is my desired output

a = 0
def iloc_backwards (df, col):
    for i in df.index:
        val1 = df[col].iloc[i]
        val2 = df[col].iloc[i+1]
        if val1 == val2 :
            a+
        else: df.at[i,col] = df.rolling(window=a).mean()

A   B   C
1   0   0.25    
2   0   0.25
3   0   0.25    
4   1   0.25
5   0   0.5
6   1   0.5

If you should take the average of all values up to the first encounter of a value that is non-zero, try this code:

df['group'] = df['B'].shift().ne(0).cumsum()
df['C'] = df.groupby('group').B.transform('mean')
df[['A', 'B', 'C']]

This corresponds with your desired output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM