繁体   English   中英

使用.loc时的SettingWithCopyWarning

[英]SettingWithCopyWarning while using .loc

问题简化了:

我需要根据一列中的文本是否具有'-'字符来提取和修改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产生我想要的结果,除了一个例外。 每次我调用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() (请参阅docs)SettingWithCopyWarning消失:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM