简体   繁体   中英

Python/Pandas - Summing DataFrame columns items

I have the following DataFrame:

            Value   Seasonal
Date                        
2004-01-01      0 -10.000000
2004-02-01    173 -50.000000
2004-03-01    225   0.000000
2004-04-01    230   9.000000

I want to sum its items so it gets like this:

                   Value 
Date                        
2004-01-01    -10.000000
2004-02-01    123.000000
2004-03-01    225.000000
2004-04-01    239.000000

Is there an easy way to do that?

If you want to create an entirely new data frame without messing up the old one.

import pandas as pd

In [12]: pd.DataFrame({"Date": df["Date"], "Value": df["Value"] + df["Seasonal"]})
Out[12]: 
         Date  Value
0  2004-01-01    -10
1  2004-02-01    123
2  2004-03-01    225
3  2004-04-01    239

你可以:

df['Value'] = df['Value'] + df['Seasonal']
df['Value'] += df['Seasonal']
dfnew = df.drop('Seasonal', axis=1)
print(dfnew)

Output:
Date  Value
0  2004-01-01    -10
1  2004-02-01    123
2  2004-03-01    225
3  2004-04-01    239

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