Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

When I try this:

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

The column contains only NaNs.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Obviously I’m missing something. And thanks for any insight.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading