将 fillna() 与当前行中的值一起使用时的SettingWithCopyWarning

d4r*_*rty 5 pandas

以下代码对表进行如下转换:

     col1  col2
0       1   3.0
1       2   4.0
2    C345   NaN
3  A56665   4.0
4   34553   NaN
5  353535   4.0

     col1   col2
0       1      3
1       2      4
2    C345   C345
3  A56665      4
4   34553  34553
5  353535      4
Run Code Online (Sandbox Code Playgroud)

import pandas as pd

d = {'col1': [1, 2, "C345", "A56665", 34553, 353535], 'col2': [3, 4,None, 4,None, 4]}
df = pd.DataFrame(data=d)
df.col1.astype(str)

print(df)

df.col2.fillna(df.col1, inplace=True)
print(df)
Run Code Online (Sandbox Code Playgroud)

然而,SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame当我在大型数据集上应用这种方法时,我遇到了一个问题。我做错了什么/没有按照预期的方式做错什么?

meW*_*meW 4

尝试使用locdf.loc[:, 'col2'].fillna(df.col1, inplace=True)

要关闭SettingWithCopyWarning单个数据帧,请使用

df.is_copy = False
Run Code Online (Sandbox Code Playgroud)

或者,

df = df.copy()
Run Code Online (Sandbox Code Playgroud)

  • `df = df.copy()` 有效 (2认同)