我正在使用pandas进行实验,并尝试将一些NaN列填充为0(同时保留其他列不变)。
这是我正在尝试的方式:
variablesToCovertToZero = ['column1', 'column2'] #just a list of columns
print('before ', df.isna().sum().sum()) #show me how many nulls
# df = df.update(df[variablesToCovertToZero].fillna(0, inplace=True)) #try 1, didn't work
df[variablesToCovertToZero].fillna(0, inplace=True) #try 2, also didn't work
print('after ', df.isna().sum().sum())
运行结果:
before 11056930
/opt/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py:4259: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
**kwargs
after 11056930
之前和之后是相同的!但我还收到了一个警告。过去警告不是问题,但我想把它加进来,以防它与此相关。
对于我做错了什么,有任何建议吗?我只想针对特定列使用填充选项。
df[variablesToCovertToZero] = df[variablesToCovertToZero].fillna(0)
并且不使用inplace,它会很好地工作。否则,如果你想要填充一些列并使用inplace,你可以这样做df.fillna({col:0 for col in variablesToCovertToZero }, inplace=True)
。 - Ben.T