首页 > 解决方案 > 计算百分比变化(熊猫)

问题描述

我正在尝试获取特定日期/月份出现的水果选择百分比,如示例中所示。

我可以通过以下行获得整个 df 的总平均值。但是,我想查看天/月的百分比变化。

df['apple%'] = df['fruit'].eq(apple).groupby(df['name']).transform('mean')

df['orange%'] = df['fruit'].eq(orange).groupby(df['name']).transform('mean')

原始df:

date    name    fruit   
1-Jan   john    apple       
1-Feb   john    orange  
1-Mar   john    apple   
1-Apr   john    apple   
1-May   john    orange  
1-Jun   john    apple   
1-Jul   john    apple   

我希望得到什么:

date    name    fruit    apple%     orange%
1-Jan   john    apple    100%   
1-Feb   john    orange   50%        50%
1-Mar   john    apple    67%        33%
1-Apr   john    apple    75%        25%
1-May   john    orange   60%        40%
1-Jun   john    apple    67%        33%
1-Jul   john    apple    71%        29%

我已经按照建议添加了 df 。非常感谢

data = {'date':['1-Jan', '1-Feb', '1-Mar', '1-Apr', '1-May', '1-Jun', '1-July'], 'name':['john', 'john', 'john', 'john', 'john', 'john', 'john'], 
 'fruit':['apple', 'orange', 'apple', 'apple', 'orange', 'apple', 'apple']} 

df = pd.DataFrame(data) 

print(df)

标签: pandas

解决方案


利用:

df['values']=(df.groupby(['fruit','name']).cumcount()+1)/(df.groupby('name')['fruit'].cumcount()+1)
df2=df.pivot_table(index=df.index,columns='fruit',values='values').rename_axis(columns=None)
df2=df2.apply(lambda x: x.fillna(1-df2.sum(axis=1)) )*100
new_df=pd.concat([df.drop('values',axis=1),df2],axis=1)
print(new_df)

输出

    date  name   fruit       apple     orange
0  1-Jan  john   apple  100.000000   0.000000
1  1-Feb  john  orange   50.000000  50.000000
2  1-Mar  john   apple   66.666667  33.333333
3  1-Apr  john   apple   75.000000  25.000000
4  1-May  john  orange   60.000000  40.000000
5  1-Jun  john   apple   66.666667  33.333333
6  1-Jul  john   apple   71.428571  28.571429


推荐阅读