我有以下数据框 df:
print(df)
Food Taste
0 Apple NaN
1 Banana NaN
2 Candy NaN
3 Milk NaN
4 Bread NaN
5 Strawberry NaN
我正在尝试使用 iloc 替换一系列行中的值:
df.Taste.iloc[0:2] = 'good'
df.Taste.iloc[2:6] = 'bad'
但它返回了以下 SettingWithCopyWarning 消息:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
所以,我找到了这个 Stackoverflow 页面 并尝试了这个:
df.iloc[0:2, 'Taste'] = 'good'
df.iloc[2:6, 'Taste'] = 'bad'
不幸的是,它返回了以下错误:
ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]
在这种情况下使用 iloc 的正确方法是什么?另外,有没有办法将上面的这两行结合起来?
原文由 Henry 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用
Index.get_loc
列的位置Taste
,因为DataFrame.iloc
按位置选择:不推荐使用
ix
的可能解决方案,因为在下一版本的 pandas 中 弃用 ix :