Pandas: Sum multiple columns, but write NaN if any column in that row is NaN or 0

MJK

I am trying to create a new column in a pandas dataframe that sums the total of other columns. However, if any of the source columns are blank (NaN or 0), I need the new column to also be written as blank (NaN)

a    b    c    d    sum

3    5    7    4    19
2    6    0    2    NaN    (note the 0 in column c)
4    NaN  3    7    NaN

I am currently using the pd.sum function, formatted like this

 df['sum'] = df[['a','b','c','d']].sum(axis=1, numeric_only=True)

which ignores the NaNs, but does not write NaN to the sum column.

Thanks in advance for any advice

BEN_YO

replace your 0 to np.nan then pass skipna = False

df.replace(0,np.nan).sum(1,skipna=False)
0    19.0
1     NaN
2     NaN
dtype: float64
df['sum'] = df.replace(0,np.nan).sum(1,skipna=False)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Pandas Set multiple column and row values to nan based on another dataframe

Remove row/columns with any/all NaN values

If NaN then sum of columns else column - Python

Pandas sum two columns, skipping NaN

How to replace NaN with sum of the row in Pandas DatatFrame

Split pandas column into new columns in presence of NaN

Fill NaN in specific row and column in Pandas

Pandas: Split cell into multiple colums, write NaN

How to remove columns after any row has a NaN value in Python pandas dataframe

Working with NaN values in multiple columns in Pandas

Python Pandas replace multiple columns zero to Nan

Pandas set multiple column and row values to nan based on another dataframe with different column headers

Sum multiple columns according to NaN status of other columns

Pandas renaming multiple NaN column names

Fill Nan based on multiple column condition in Pandas

Print Row and Column Header if column/row is not NaN Pandas

Combine multiple categorical columns into one, when each row has only one non-NaN value, in Pandas

Python/Pandas: if value is NaN or 0 then fill with the value from the next column within the same row

compare two columns row by row and nan duplicate values pandas

Pandas Row mean with NaN

Sum of dataframe columns to another dataframe column Python gives NaN

Replace 0 with NaN for selected columns only if all values are 0 in Pandas

Pandas move column values to first row within same column if Nan

How to find which columns contain any NaN value in Pandas dataframe

Pandas dropping all the columns that contain any nan except one

Pandas - drop row containing Nan and then drop any associated rows

Replace multiple strings and numbers from multiple columns with NaN in Pandas

Pandas pivot_table replaces nan with 0 aggfunc='sum'

How to sum 2 pandas Series with diffent rows treating NaN as 0