中使用iloc的正确方法

中使用iloc的正确方法

本文介绍了在 pandas 中使用iloc的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有以下数据框df:

print(df)

    Food         Taste
0   Apple        NaN
1   Banana       NaN
2   Candy        NaN
3   Milk         NaN
4   Bread        NaN
5   Strawberry   NaN

我正在尝试使用iloc替换一系列行中的值:

I am trying to replace values in a range of rows using iloc:

df.Taste.iloc[0:2] = 'good'
df.Taste.iloc[2:6] = 'bad'

但是它返回了以下SettingWithCopyWarning消息:

But it returned the following SettingWithCopyWarning message:

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

因此,我找到了 Stackoverflow页面,并尝试了以下方法:

So, I found this Stackoverflow page and tried this:

df.iloc[0:2, 'Taste'] = 'good'
df.iloc[2:6, 'Taste'] = 'bad'

不幸的是,它返回了以下错误:

Unfortunately, it returned the following error:

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的正确方法是什么?另外,有没有办法将上面的这两行结合起来?

What would be the proper way to use iloc in this situation? Also, is there a way to combine these two lines above?

推荐答案

您可以使用 Index.get_loc 用于列Taste的位置,因为 DataFrame.iloc 按位置选择:

You can use Index.get_loc for position of column Taste, because DataFrame.iloc select by positions:

#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解决方案,因为在下一个版本的熊猫中弃用ix :

Possible solution with ix is not recommended because deprecate ix in next version of 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

这篇关于在 pandas 中使用iloc的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 20:51