python - 在 Pandas 中使用 iloc 的正确方法

标签 python pandas dataframe match

我有以下数据框 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/

相关文章:

python - 自版本 2.0.0 以来 Bokeh 图损坏

python - 使用 Python Marshmallow 进行数据类型转换

python - 在 Pandas 中拆分、分组、组合以查找日期差异

python - 连接两个 Pandas .HDFStore HDF5文件

python - 如何使用Python数据集中的条件更新相同的字段?

python pandas dataframe 连接两个数据框

python - 更改 Dataframe 的列名后出现关键错误

python - Pandas 数据框 : select multiple rows based on entries in other rows

python数据框到excel

python - pandas DataFrame 中的条件操作