eponkratova
eponkratova

Reputation: 477

If NaN then sum of columns else column - Python

I have the dataset:

enter image description here

The logic to be implemented: if prev_product_id is NaN then payment1+payment2 else payment2.

enter image description here

I've tried with the list comprehension:

column_names = ['payment1', 'payment2']
df['payment_corrected']= [df[column_names].sum(axis=1) if math.isnan(float(i))==True else df['payment2'] for i in df['prev_product_id']]

But got:

enter image description here

Why is there an array instead of row by row summation?

Upvotes: 1

Views: 94

Answers (1)

lionking-123
lionking-123

Reputation: 311

You can change the code as below :

df["payment_corrected"] = df["payment2"]
df["payment_corrected"][(df["prev_product_id"].isna())] = df["payment1"][(df["prev_product_id"].isna())] + df["payment2"][(df["prev_product_id"].isna())]

Hope to be helpful for you.

Upvotes: 1

Related Questions