Home > other >  Want to create a new column named 'sum_columns', which is the sum of all numeric columns i
Want to create a new column named 'sum_columns', which is the sum of all numeric columns i

Time:11-05

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.

CodePudding user response:

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
  • Related