2

I'm trying to replace nulls in few columns of pandas dataframe by fillna.

df["A"].fillna("Global", inplace=True)
df["B"].fillna("Global", inplace=True)
df["C"].fillna("Global", inplace=True)
df["D"].fillna("Global", inplace = True)

The nulls don't seem to be replaced completely as df.isnull().sum() still returns non-zero values for columns A,B,C and D.

I have also tried the following, it doesn't seem to make a difference.

df["A"] = df["A"].fillna("Global", inplace=True)
df["B"] = df["B"].fillna("Global", inplace=True)
df["C"] = df["C"].fillna("Global", inplace=True)
df["D"] = df["D"].fillna("Global", inplace=True)

Following is my Sample data which contains NAN

id                 A        B                             D
630940            NaN       NaN         ...             NaN   
630941            NaN       NaN         ...             NaN
4

1 回答 1

1

Inplace fillna does not work on pd.Series columns because they return a copy, and the copy is modified, leaving the original untouched.

Why not just do -

df.loc[:, 'A':'D'] = df.loc[:, 'A':'D'].fillna('Global') 

Or,

df.loc[:, ['A', 'B', 'C', 'D']] = df.loc[:, ['A', 'B', 'C', 'D']].fillna('Global')
于 2018-04-05T22:54:41.433 回答