使用 .loc 时的 SettingWithCopyWarning

Lis*_*sle 2 python pandas

问题简化:

我需要根据列中DataFrame的文本是否具有“-”字符来提取和修改 a 的特定行。破折号和后面的所有内容都需要删除,剩余的文本需要是“-”之前的任何内容。

have:
     textcol
0    no dash here
1    one - here

want:
     textcol
0    one
Run Code Online (Sandbox Code Playgroud)

这是用于重新创建我的场景的代码。

df = pd.DataFrame(data=['no dash here', 'one - here'], index=[0, 1], columns=['textcol'])
df2 = df[df['textcol'].str.contains('-') == True]
df2.loc[:, ['textcol']] = df2['textcol'].str.split('-').str[0]
Run Code Online (Sandbox Code Playgroud)

结果DataFramedf2 产生了我想要的结果,只有一个例外。每次我打电话给 df2(或之后的任何衍生产品)时,我都会收到以下信息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/indexing.html#indexing-view-versus-copy
Run Code Online (Sandbox Code Playgroud)

我试图以不同的方式完成我想要的事情,并得到了一个类似的错误,指示我尝试使用 .loc()功能,但我仍然收到这个类似的错误。

有没有更好的、无错误威胁的方式来完成这个结果?恐怕这里发生了一些我不明白的事情,最终 df2 不会产生我想要的结果。我也想知道类似的东西.query()是否可行。

Ste*_*fan 6

正如@EdChum 所提到的,df2是一个viewondf而不是copy. 如果你想要一个copy,你可以使用.copy() (参见文档)然后SettingWithCopyWarning消失:

df2 = df[df['textcol'].str.contains('-') == True].copy()
df2.loc[:, ['textcol']] = df2['textcol'].str.split('-').str[0]
Run Code Online (Sandbox Code Playgroud)

请参阅文档中的返回视图与副本pandas。