1

I have a pandas dataframe:

    Col1  Col2  Col3
0    1     2     3
1    2     3     4

And I want to add a new row summing over two columns [Col1,Col2] like:

      Col1  Col2  Col3
0      1     2     3
1      2     3     4
Total  3     5     NaN

Ignoring Col3. What should I do? Thanks in advance.

1
  • When you say dataframe, do you mean pandas? Then it should be tagged accordingly. And what have you tried, why did it fail? Commented Jul 7, 2018 at 9:37

2 Answers 2

1

You can use the pandas.DataFrame.append and pandas.DataFrame.sum methods:

df2 = df.append(df.sum(), ignore_index=True)
df2.iloc[-1, df2.columns.get_loc('Col3')] = np.nan
Sign up to request clarification or add additional context in comments.

1 Comment

jpp's answer is better, as it doesn't calculate the third column
0

You can use pd.DataFrame.loc. Note the final column will be converted to float since NaN is considered float:

import numpy as np

df.loc['Total'] = [df['Col1'].sum(), df['Col2'].sum(), np.nan]
df[['Col1', 'Col2']] = df[['Col1', 'Col2']].astype(int)

print(df)

       Col1  Col2  Col3
0         1     2   3.0
1         2     3   4.0
Total     3     5   NaN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.