此代码的执行有效:
import pandas as pd
df = pd.DataFrame({'name':["Adam","Sarah","Tom","Adam","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]
请参阅文档中的警告: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df [colName] [(df [colName]> 10)&(df [colName]
请参阅文档中的警告: 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作为第二个参数是违反直觉的...