lcasucci
lcasucci

Reputation: 87

How to substitute the 0 and nan values of a pandas pivot table with the row average?

I used this to substitute the nan values with the row average for my pivot table

pivot = pivot.apply(lambda row: row.fillna(row.mean()), axis=1)

However, how can I include the row values that are 0 in the transformation (transform both nan and 0 with the row average)?

I tried to apply a lambda function before executing the command above to transform the 0 values in nan, but it did not work. Below what I tried to convert 0s to nan :

pivot = pivot.apply(lambda x == np.nan if x == 0 else x )

Upvotes: 0

Views: 299

Answers (1)

pykam
pykam

Reputation: 1481

There are syntax issues with your lambda function.

Firstly you need to declare the input variable of the lambda.

Secondly when you assign something use = instead of ==.

Edit - You can't make assignments within a lambda so just writing np.nan should do.

Can you try this instead.

pivot = pivot.apply(lambda x: np.nan if x == 0 else x )

Upvotes: 1

Related Questions