python - 使用 .loc 时的 SettingWithCopyWarning

标签 python pandas

问题被简化了:

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

have:
     textcol
0    no dash here
1    one - here

want:
     textcol
0    one

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

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]

生成的 DataFrame df2 产生了我想要的结果,但有一个异常(exception)。每次调用 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

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

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

最佳答案

如@EdChum 所述,df2df 上的view,而不是copy。如果你想要一个copy,你可以使用.copy() (see docs) SettingWithCopyWarning 消失了:

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

参见 returning a view vs copypandas 文档中。

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

相关文章:

python - python 扩展上的地址 sanitizer

python - 如何让用户结束程序和类次表

python - Pandas : reshape 数据

python - 使用 Pandas/Python 在数据框中查找最接近的匹配数字

python pandas read_csv 如何解析微秒

python - 在 GAE 项目中包含和引用第 3 方库

python - 在 matplotlib 中使用循环变量指定颜色

python - 不同分组重复组的累积总和

python - 如何仅转置数据框的一部分或交换行和列?

python - Pandas 数据框中的字符串列操作