Home > Mobile >  pandas: fillna(method="pad") "NaN" values but not "None"
pandas: fillna(method="pad") "NaN" values but not "None"

Time:12-25

Is there a way to (forward) fill only "NaN" values and not "None"?. For example, I have a df:

   A     B     C
0  12    0    None
1  None  NaN  None
2  NaN   9.8  1
3  0     NaN  1

Appyling df.fillna(method="pad") will replace all NaN AND None values. I want to exclude "None" values from the fill ops and leave them unchanged.

Expected:

   A     B     C
0  12    0   None
1  None  0   None
2  None  9.8  1
3  0     9.8  1

CodePudding user response:

We can replace then ffill

yourdf = df.replace({None:'None'}).ffill().replace({'None':None})
      A    B     C
0    12  0.0  None
1  None  0.0  None
2  None  9.8     1
3     0  9.8     1

CodePudding user response:

DataFrame:

df = df.fillna(value=np.nan)

Series/Column:

df.mycol.fillna(value=np.nan, inplace=True)

You can also use the replace method:

df['column'].replace('None', np.nan, inplace=True)
  • Related