熊猫:分组依据对象的百分比变化

时间:2018-12-14 17:08:20

标签: python-3.x pandas lambda pandas-groupby

我需要有关pandas groupby的帮助。有没有一种方法可以对pandas groupby中的每个组运行lambda(或等效值)?请参见下面的示例。我想在此分组依据的右边一栏中添加与上一年相比的百分比变化。我尝试了几种方法,但是它们似乎都忽略了从新的“项目”组开始的方法。

import pandas as pd
x = pd.Series(['Oranges', 'Apples', 'Other Fruits', 'Oranges', 'Apples', 'Other Fruits', 'Oranges', 'Apples', 'Other Fruits'])
y = pd.Series([2016, 2016, 2016, 2017, 2017, 2017, 2018, 2018, 2018])
z = pd.Series([12, 15, 9, 14, 15, 50, 32, 15, 12])
df = pd.DataFrame({'Item': x, 'Year':y, 'Values':z})
df=df.sort_values('Values', ascending=False) 
df.groupby(['Item', 'Year']).sum()
#How do I get Percent % Values for each group as a new column right of 'Values'

我期望以下几点:

Results Expected

1 个答案:

答案 0 :(得分:1)

您要使用GroupBy寻找apply + pct_change

# Sort DataFrame before grouping.
df = df.sort_values(['Item', 'Year']).reset_index(drop=True)
# Group on keys and call `pct_change` inside `apply`.
df['Change'] = df.groupby('Item', sort=False).Values.apply(
     lambda x: x.pct_change()).values

df
           Item  Year  Values    Change
0        Apples  2016      15       NaN
1        Apples  2017      15  0.000000
2        Apples  2018      15  0.000000
3       Oranges  2016      12       NaN
4       Oranges  2017      14  0.166667
5       Oranges  2018      32  1.285714
6  Other Fruits  2016       9       NaN
7  Other Fruits  2017      50  4.555556
8  Other Fruits  2018      12 -0.760000