问题被简化了:
我需要根据列中的文本是否具有“-”字符来提取和修改 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 所述,df2
是df
上的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 copy在 pandas
文档中。
关于python - 使用 .loc 时的 SettingWithCopyWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34622245/