累积和百分比列?

编程入门 行业动态 更新时间:2024-10-26 08:26:04
本文介绍了累积和百分比列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 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.

更多推荐

累积和百分比列?

本文发布于:2023-10-30 08:06:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542266.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:百分比

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!