首页 > 解决方案 > 更改熊猫列中的值:SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame error

问题描述

所以我有这个名为matches的 pandas df ,它有两列“线程”和“当前电子邮件”。“当前电子邮件”是从另一个名为df的 df复制的:

matches['Current email'] = df['description']

Thread 只有两个值:threadnot thread。因此,如果电子邮件是一个线程,我想将具有相同索引的“当前电子邮件”值更改为 8(实际上是另一件事,但为了便于理解 8)。

for index,value in matches['Thread'].iteritems():
  if value=='not thread':
    pass 
  else:
    matches.iloc[index]['Current email'] = 8 

运行此警告后/usr/local/envs/py3env/lib/python3.5/site-packages/ipykernel/__main__.py:5: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame过来。

我试过这样的事情:

matches['Current email'] = df['description'].copy()

更奇怪的是,相同的代码也适用于其他数据。

有什么帮助吗?

标签: pythonpandas

解决方案


您可以使用布尔索引:

filter_thread = matches['Thread'] != 'not thread'
matches.loc[filter_thread, 'Current email'] = 8

推荐阅读