Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用.loc时设置CopyWarning_Python_Pandas - Fatal编程技术网

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,我仍然收到相同的错误:(