gpt4 book ai didi

python - pandas 使用列子集时的SettingWithCopyWarning

转载 作者:太空宇宙 更新时间:2023-11-03 16:33:05 24 4
gpt4 key购买 nike

我试图了解pandasSettingWithCopyWarning,到底是什么触发了它以及如何避免它。我想从数据框中选择一些列,然后使用这些选择的列。我需要填充缺失值并将所有大于 1 的值替换为 1。

我知道 sub_df=df[['col1', 'col2', 'col3']] 会生成一个副本,这似乎就是我想要的。有人可以解释为什么这里会触发复制警告,这是否有问题,以及我应该如何避免它?

我在这种情况下阅读了很多有关链式赋值的内容,我在这里这样做吗?

data={'col1' : [25 , 0, 100, None],
'col2' : [50 , 0 , 0, None],
'col3' : [None, None, None, 100],
'col4' : [ 20 , 20 , 20 , 20 ],
'col5' : [1,1,2,3]}
df= pd.DataFrame(data)
sub_df=df[['col1', 'col2', 'col3']]
sub_df.fillna(0, inplace=True)
sub_df[df>1]=1 # produces the copy warning
sub_df

真正让我困惑的是,如果我没有为我的列子集使用新名称,为什么不会触发此警告,如下所示:

data={'col1' : [25 , 0, 100, None],
'col2' : [50 , 0 , 0, None],
'col3' : [None, None, None, 100],
'col4' : [ 20 , 20 , 20 , 20 ],
'col5' : [1,1,2,3]}
df= pd.DataFrame(data)
df=df[['col1', 'col2', 'col3']]
df.fillna(0, inplace=True)
df[df>1]=1 # does not produce the copy warning
df

谢谢!

最佳答案

您的两个代码片段在语义上是不同的,在第一个代码片段中,您是否想要对原始 df 的 View 或副本进行操作是不明确的,在第二个代码片段中,您用 df 的子集覆盖 df df 所以没有歧义。

如果您想对副本进行操作,请执行以下操作:

sub_df=df[['col1', 'col2', 'col3']].copy()

如果您想对 View 进行操作,那么我建议使用列列表并使用新的 indexers 引用它们。像下面这样:

df[col_list].fillna(0) 

然后

df.loc[df > 1, col_list] = 1

关于python - pandas 使用列子集时的SettingWithCopyWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37435468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com