本文介绍了累积和百分比列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 DataFrame 这样:
df :
fruit val1 val2 0 orange 15 3 1 apple 10 13 2 mango 5 5如何让熊猫给我累积的总和百分比列只有 val1 ?
How do I get Pandas to give me a cumulative sum and percentage column on only val1?
所需输出:
df_with_cumsum :
fruit val1 val2 cum_sum cum_perc 0 orange 15 3 15 50.00 1 apple 10 13 25 83.33 2 mango 5 5 30 100.00我试过 df.cumsum(),但它给我这个错误:
I tried df.cumsum(), but it's giving me this error:
TypeError:输入类型不支持ufunc'isnan',根据转换规则'safe'',输入无法安全地强制转换为任何支持的类型。
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
推荐答案
df['cum_sum'] = df.val1.cumsum() df['cum_perc'] = 100*df.cum_sum/df.val1.sum()
这将添加列到 df 。如果您需要副本,请先复制 df ,然后在副本上执行这些操作。
This will add the columns to df. If you want a copy, copy df first and then do these operations on the copy.
更多推荐
累积和百分比列?
发布评论