Home > Mobile >  Check if all values in a row are NaN and replace them with 0
Check if all values in a row are NaN and replace them with 0

Time:10-23

I am have a pandas data frame that has about 2000 rows and 8000 columns. I am trying to check if there are any rows with all values are NaN and if that is the case then replace NaN with 0. I am aware that we can use the below code to check but I am not sure on how to further build it to replace the NaN (s).

Note - I do not want to replace NaN on a column level.

Could someone please help?

df_june.isna().all(axis=1)  # to check if all values of a row are NaN.

CodePudding user response:

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html#pandas.DataFrame.fillna

df_june.fillna(0, inplace=True)

CodePudding user response:

import pandas as pd
df = pd.DataFrame({"a": [None, "12", None], "b": [None, None, "34"]})
df[df.apply(lambda row: [row[x] is None for x in df.columns].count(True)==len(df.columns), axis=1)] = 0
print(df)
  • Related