Proper way to use iloc in Pandas

前端 未结 4 1205
故里飘歌
故里飘歌 2020-12-14 04:39

I have the following dataframe df:

print(df)

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


        
4条回答
  •  我在风中等你
    2020-12-14 05:29

    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
    

    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
    

提交回复
热议问题