Python 上一行之前的值的Groupby

Python 上一行之前的值的Groupby,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,如果每个水果的值低于上一行的值,如何添加布尔值?如果是的话,前5年的平均值是多少 fruit year value apple 1950 2 apple 1951 3 apple 1952 3 apple 1953 4 apple 1954 5 apple 1955 4 banana 1950 333 banana 1951 335 试试这个: Expected Outpu

如果每个水果的值低于上一行的值,如何添加布尔值?如果是的话,前5年的平均值是多少

fruit   year     value 
apple   1950      2
apple   1951      3
apple   1952      3
apple   1953      4
apple   1954      5
apple   1955      4
banana  1950     333
banana  1951     335 

试试这个:

Expected Output
fruit   year     value  lower_than_before  5 year avg
apple   1950      2
apple   1951      3
apple   1952      3
apple   1953      4
apple   1954      5
apple   1955      4       True                 3.4
banana  1950     333
banana  1951     335 
输出:

g = df.groupby('fruit')
df['lower_than_before'] = g['value'].diff().lt(0)
df['5 year avg'] = g['value'].apply(lambda x: x.rolling(5).mean().shift().where(df['lower_than_before'].cummax()))
df
df['lower_than_before'] = np.where((df.value - df.value.shift(1)) < 0, True, '')

df['5 year avg'] = np.where(df.lower_than_before=='True', df.value.rolling(window=5, min_periods=0).mean().shift(1), '')

使用shift函数并处理NaN,如下所示:

    fruit  year  value  lower_than_before  5 year avg
0   apple  1950      2              False         NaN
1   apple  1951      3              False         NaN
2   apple  1952      3              False         NaN
3   apple  1953      4              False         NaN
4   apple  1954      5              False         NaN
5   apple  1955      4               True         3.4
6  banana  1950    333              False         NaN
7  banana  1951    335              False         NaN

5年平均值相对于每个水果在该布尔行之前的5年平均值。这里5+4+3+3+2=17。那么17/5=3.4对不起,在一个True之后也可以做5年的平均值吗?在我的样本数据中,1955年之后没有年份,但原则上应该是1956年到2000年的平均值“条件预期的布尔数组,而不是对象”@asd检查键入。。。这似乎是这些语句的
where
部分的错误。df['lower_than_before']应该是一个布尔级数。@ScottBoston真棒,我在想什么是解决相对5年平均值的最佳方法,但你的方法非常有效。谢谢!对不起,也可以在一个真值之后计算5年平均值吗?是的,请尝试以下代码:df['5年平均值]=np.where((df.lower_than_before='True'))(df.lower_than_before.shift(1)='True')),df.value.rolling(window=5,min_periods=0.mean().shift(1),“”)嗯,5年后,有些人似乎没有给出正确的答案reason@asd在第5行中,前5年的平均值应该是3.4,在第6行中,它应该是3.8,这与代码的输出相匹配。@asd尝试一下这个代码:df['5年后的平均值]=np.where(df.lower\u-before='True',df.value.shift(-5)。滚动(窗口=5,最小周期=0)。平均值(),“”)
    fruit  year  value lower_than_before 5 year avg
0   apple  1950      2                             
1   apple  1951      3                             
2   apple  1952      3                             
3   apple  1953      4                             
4   apple  1954      5                             
5   apple  1955      4              True        3.4
6  banana  1950    333                             
7  banana  1951    335