我有以下数据框 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 page并试过这个:
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 的正确方法是什么?另外,有没有办法将上面的这两行结合起来?
最佳答案
您可以使用 Index.get_loc
Taste
列的位置,因为 DataFrame.iloc
按职位选择:
#return second position (python counts from 0, so 1)
print (df.columns.get_loc('Taste'))
1
df.iloc[0:2, df.columns.get_loc('Taste')] = 'good'
df.iloc[2:6, df.columns.get_loc('Taste')] = 'bad'
print (df)
Food Taste
0 Apple good
1 Banana good
2 Candy bad
3 Milk bad
4 Bread bad
5 Strawberry bad
不推荐使用 ix
的可能解决方案,因为 deprecate ix在下一个版本的 Pandas 中:
df.ix[0:2, 'Taste'] = 'good'
df.ix[2:6, 'Taste'] = 'bad'
print (df)
Food Taste
0 Apple good
1 Banana good
2 Candy bad
3 Milk bad
4 Bread bad
5 Strawberry bad
关于python - 在 Pandas 中使用 iloc 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42139624/