Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

python - Cumulative sum and percentage on column?

I have a DataFrame like this:

df:

 fruit    val1 val2
0 orange    15    3
1 apple     10   13
2 mango     5    5 

How do I get Pandas to give me a cumulative sum and percentage column on only val1?

Desired output:

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

I tried df.cumsum(), but it's giving me this error:

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''

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
df['cum_sum'] = df['val1'].cumsum()
df['cum_perc'] = 100*df['cum_sum']/df['val1'].sum()

This will add the columns to df. If you want a copy, copy df first and then do these operations on the copy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...