在pandas中修改单列时出现SettingWithCopyWarning
我最近开始使用pandas来处理数据。在修改某一列(比如去掉空格和删除字符)时,我遇到了一个叫做SettingWithCopyWarning的警告,代码是这样的:
dframe['title'] = dframe['title'].str.strip()
dframe['title'] = dframe['title'].str.upper().replace([";", ":"], "", regex=True)
之前我导入了一个Excel文件,并使用df.iloc[]
来选择我想要处理的列,还给这些列重新命名。我已经尝试把这个df.iloc[]
赋值给一个新变量,但警告还是一直出现。因为我刚开始学习pandas,所以我不想马上就忽略这个警告,因为我觉得应该有更好的解决办法。
这个警告是:
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
dframe['title'] = dframe['title'].str.upper().replace([";", ":"], "", regex=True)
c:/file.py:45: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
相关问题:
- 暂无相关问题
2 个回答
0
我觉得如果你在两边都使用 .loc 的话,应该可以消除这个警告。
dframe.loc[:, 'title'] = dframe.loc[:, 'title'].str.strip()
如果这样有效,请告诉我,因为这个警告让我烦恼了很多次,肯定也让很多其他人困扰过 :)
1
试着用 apply 这个方法,而不是直接对数据的切片进行变换。
这样你的代码就变成了:
dframe['title'] = dframe['title'].apply(lambda x: str(x).strip())
dframe['title'] = dframe['title'].apply(lambda x: str(x).upper().replace(":", "").replace(";", ""))