Reputation: 333
I have a dataframe which has many columns, I want to insert a new row to calculate the sum of the last 2 columns. I tried to use concat function but doesnt works. It add a new column not a new row. Is there has a solution?
Dataframe looks like this:
Date. A. B. C. D
2021-03-01 5. 10. 15. 20
2021-03-02 5. 10 5. 5
2021-03-03.5. 10. 10. 5
I tried to create a blank dataframe and concat the original DataFrame but the output was wrong.
new_df = pd.DataFrame(columns=['Date'])
merge_df = pd.concat([returns,new_df])
I want the result like that:
Date. A. B. C. D
2021-03-01 5. 10. 15. 20
2021-03-02 5. 10 5. 5
2021-03-03.5. 10. 10. 5
sum_2 10 20. 15. 10
Upvotes: 1
Views: 1157
Reputation: 511
You can use pandas sum() function for this, by summing along the index.
Something like this.
df.loc['sum_2',:]= df.sum(axis=0)
Upvotes: 1
Reputation: 14949
try this also -
result = df[df._get_numeric_data().columns.values].iloc[-2:,:].sum()
df.append(result, ignore_index=True)
Upvotes: 1
Reputation: 2132
Adding df:
import pandas as pd
df = pd.DataFrame({
"A": [5, 10, 15, 20],
"B": [5, 10, 15, 5],
"C": [5, 10, 5, 5],
"D": [5, 10, 10, 5]})
Summing total:
df.loc["Row_Total"] = df.sum()
df
Summing only last 2 rows:
iloc - https://www.kite.com/python/answers/how-to-get-the-last-n-rows-from-a-pandas-dataframe-in-python
https://www.kite.com/python/docs/pandas.DataFrame.iloc
df.loc["Row_Total"] = df.iloc[-2:].sum()
Upvotes: 2