pandas - 计算百分比变化(熊猫)
问题描述
我正在尝试获取特定日期/月份出现的水果选择百分比,如示例中所示。
我可以通过以下行获得整个 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)
解决方案
利用:
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
推荐阅读
- deep-learning - 如何从 Google Colab 访问笔记本电脑摄像头以在实时流视频中进行对象检测?
- javascript - 在外部单击时,Ion-Input 不会失去焦点
- javascript - webgl 使用帧缓冲区对象在图像上的多个片段着色器提供黑色输出
- pyspark - flatMapValues(whole_list,一个元素列表)
- node.js - 带有所有路由的 Node.js Express API“无法获取”。适用于本地主机但不适用于我的服务器
- pandas - 如何更正代码?尝试使用带有 lambda if/else 语句的列表推导式使用 pandas 输出
- grouping - 按进程分组标签
- javascript - React Native 图像 web uri 不适用于真实设备(在模拟器中工作)
- python - 如何设置从传感器获取输入并对其进行分析的python程序?
- reactjs - React useSelector hook 是传播对象还是只指定需要的字段更好