Python 使用.loc时设置CopyWarning
问题简化了: 我需要根据列中的文本是否具有“-”字符来提取和修改数据帧的特定行。破折号及其以外的所有内容都需要删除,剩下的文本必须是“-”之前的内容Python 使用.loc时设置CopyWarning,python,pandas,Python,Pandas,问题简化了: 我需要根据列中的文本是否具有“-”字符来提取和修改数据帧的特定行。破折号及其以外的所有内容都需要删除,剩下的文本必须是“-”之前的内容 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], column
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(或其后的任何衍生工具)时,我都会收到以下带有CopyWarning的设置:
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
上的视图,而不是副本。如果您需要复制
,可以使用.copy()
,然后设置WithCopyWarning
将消失:
df2 = df[df['textcol'].str.contains('-') == True].copy()
df2.loc[:, ['textcol']] = df2['textcol'].str.split('-').str[0]
请参见pandas
文档中的内容。当您分配到df2
时,您已经获取了一个视图/副本,您希望直接对df进行操作:df.loc[df['textcol'].str.contains('-'),'textcol']=df['textcol'].str.split('-').str[0]
我认为应该这样做work@EdChum,我仍然收到相同的错误:(