首页 > 解决方案 > 替换 Python 数据框特定列的特定值会引发“SettingWithCopyWarning”

问题描述

此代码的执行工作:

import pandas as pd


df = pd.DataFrame({'name':["Adam", "Sarah", "Tom", "Sarah", "Adam", "Tom", "Will"], 'score':[1,16,2,32,11,9,50]})

print(df)

colName = 'score'
df[colName][df[colName] <= 10] = 1
df[colName][(df[colName] > 10) & (df[colName] <= 20)] = 11
df[colName][df[colName] > 20] = 21

print(df)

...但抛出此警告:

test.py:9:SettingWithCopyWarning:试图在 DataFrame 中的切片副本上设置值

请参阅文档中的注意事项:http: //pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df[colName][df[colName] < = 10] = 1 test.py:10: SettingWithCopyWarning: 试图在 DataFrame 中的切片副本上设置值

请参阅文档中的警告:http: //pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df[colName][(df[colName] > 10) & (df[colName] <= 20)] = 11 test.py:11: SettingWithCopyWarning: 试图在数据帧的切片副本上设置值

请参阅文档中的注意事项:http: //pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df[colName][df[colName] > 20] = 21

我想这是深/浅复制的问题?但是我该如何解决呢?必须有一种简单易读的方法来进行如此简单的操作吗?

编辑:它适用于:

df.loc[df[colName] <= 10, colName] = 1

...但这有点不合逻辑,因为 colName 作为第二个参数是违反直觉的...

标签: pythondataframe

解决方案


试试下面的代码,希望这会有所帮助。

import pandas as pd
import numpy as np

df = pd.DataFrame({'name':["Adam", "Sarah", "Tom", "Sarah", "Adam", "Tom", "Will"], 'score':[1,16,2,32,11,9,50]})

print(df)

colName = 'score'
df[colName] = np.where(df[colName] <= 10, 1, df[colName])
df[colName] = np.where((df[colName] > 10) & (df[colName] <= 20), 11 , df[colName])
df[colName] = np.where(df[colName] > 20, 21 , df[colName])
print(df)

输出将是:

  name  score
0   Adam      1
1  Sarah     16
2    Tom      2
3  Sarah     32
4   Adam     11
5    Tom      9
6   Will     50

****NEW*********


    name  score
0   Adam      1
1  Sarah     11
2    Tom      1
3  Sarah     21
4   Adam     11
5    Tom      1
6   Will     21

这不会给出任何警告,因为您没有处理数据帧的任何部分,而是使用条件子句并更新列的值。


推荐阅读