Want to create a new column named 'sum_columns', which is the sum of all numeric columns in df

Question:

I have a DataFrame. I want to create a new column, named sum_columns, which is the sum of all existing numeric columns. When I try this:

df["sum_columns"] = df.select_dtypes(include="number").apply(np.sum)

The column contains only NaNs.

Obviously I’m missing something.

Asked By: Winston Lee

||

Answers:

import pandas as pd

df = pd.DataFrame({"col1": ['a', 'b', 'c'],
                   "col2": [1, 2, 3],
                   "col3": ['d', '1', 2],
                   "col4": [4, 5, 6]})

df['sum_col'] = df.select_dtypes(include='number').sum(axis=1)
print(df)


  col1  col2 col3  col4  sum_col
0    a     1    d     4        5
1    b     2    1     5        7
2    c     3    2     6        9
Answered By: vignesh kanakavalli
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.