简体   繁体   中英

How to locate specific values and sum them in pandas

I need help with some problem that I've been having for a couple of days.

I have a dataframe that looks like this:

0   Stage    |Value1| Value2 | Value3       
1  Complete  |  4   |   5    |   0
2 Incomplete |  2   |   1    |   4
3  Pending   |  0   |   1    |   0

I'm trying to have another row at the end of the data frame such as

0    Stage           |Value1| Value2 | Value3       
1   Complete         |  4   |   5    |   0
2  Incomplete        |  2   |   1    |   4
3   Pending          |  0   |   1    |   0
4 Complete + Pending |  4   |   6    |   0

So far, I've tried to locate the Complete and the Pending rows and assign it to a variable, but I can't manage to separate them and treat the columns differently such as to basically do

var1 = df['Stage']['Value1'] == 'Complete' 
print(var1)
>>> 4 

I've tried different ways for two days without getting the results that I want.

Try:

sum_data = (df[df.Stage=='Complete'].drop('Stage', axis=1) + df[df.Stage=='Pending'].drop('Stage', axis=1).values)
new_row = pd.concat((pd.DataFrame({'Stage':['Complete + Pending']}), sum_data), axis=1)
final_df = pd.concat((df, new_row), axis=0)
print(final_df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM