Skip to content
Advertisement

Pandas replace all items in a row with NaN if one value is NaN

I want to get rid of some records with NaNs. This works perfectly:

df.dropna(axis=0, how='any',inplace=True)

However, it changes the shape of my dataframe, and the index is no longer uniformly spaced. Therefore, I’d like to replace all items in these rows with np.nan. Is there a simple way to do this?

I was thinking about resampling the dataframe after dropna, but that only seems to work with a prescribed interval, whereas I would rather use the original index. Another approach would be to loop over the dataframe with iterrows, but that also feels cumbersome.

Advertisement

Answer

The command below selects all rows with any value equal to Nan, and assigns NaNs to the rest of those rows.

df.loc[df.isnull().any(axis=1), :] = np.nan
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement