Reputation: 1314
I have the following pandas dataframe:
2019 Jan 2019 Mar 2019 Apr 2019 May 2019 Jun
CASC\n 2.0 2.0 2.0 1.0 2.0
SpaceX\n 1.0 1.0 1.0 2.0 2.0
which you can get using the following code:
import pandas as pd
data_dict = {
'2019 Jan': {' CASC\n': 2.0, ' SpaceX\n': 1.0},
'2019 Mar': {' CASC\n': 2.0, ' SpaceX\n': 1.0},
'2019 Apr': {' CASC\n': 2.0, ' SpaceX\n': 1.0},
'2019 May': {' CASC\n': 1.0, ' SpaceX\n': 2.0},
'2019 Jun': {' CASC\n': 2.0, ' SpaceX\n': 2.0}
}
pd.DataFrame.from_dict(data_dict)
I wanted to make each column to be a sum of all the previous columns, so the final dataframe would be like this:
2019 Jan 2019 Mar 2019 Apr 2019 May 2019 Jun
CASC\n 2.0 4.0 6.0 7.0 9.0
SpaceX\n 1.0 2.0 3.0 5.0 7.0
I could get a sum of all the columns and make it a new column with this code:
df['Total'] = df.iloc[:,:].sum(axis=1)
which would result in the following dataframe:
2019 Jan 2019 Mar 2019 Apr 2019 May 2019 Jun Total
CASC\n 2.0 2.0 2.0 1.0 2.0 9.0
SpaceX\n 1.0 1.0 1.0 2.0 2.0 7.0
but it is obviously not what I want. Instead I want each column act as "Total" for the previous columns and itself. Does anybody know how to do it?
Upvotes: 1
Views: 536
Reputation: 7627
df=df.cumsum(axis=1)
print(df)
Prints:
2019 Jan 2019 Mar 2019 Apr 2019 May 2019 Jun
CASC\n 2.0 4.0 6.0 7.0 9.0
SpaceX\n 1.0 2.0 3.0 5.0 7.0
Upvotes: 2