问题被简化:
我需要根据列中的文本是否有“ - ”字符来提取和修改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()
这样的东西是否会起作用。
答案 0 :(得分:4)
如@EdChum所述,df2
与view
相比df
copy
。如果您需要copy
,可以使用.copy()
(see docs),SettingWithCopyWarning
消失:
df2 = df[df['textcol'].str.contains('-') == True].copy()
df2.loc[:, ['textcol']] = df2['textcol'].str.split('-').str[0]
请参阅pandas
文档中的returning a view vs copy。