按值,熊猫访问另一列

时间:2014-05-06 04:39:43

标签: python python-2.7 pandas indexing label

我的数据框如下:

    Type      Name           Category              
    Bird      Flappy Bird    Air      
    Bird      Pigeon         Air    
    Pokemon   Jerry          Aquatic      
    Pokemon   Mudkip         Aquatic
    Animal    Lion           Terrestrial
    Bird      Pigeon         Air2  

对于像"Pigeon"这样的给定名称,我需要访问类别列中的相应值,即它应该给我字符串"Air"
我有Pigeon的2个值,但我需要返回“Air”进行第二次观察。

请注意,我根本没有使用索引,因此使用iloc进行第二次观察会不会这样做。我需要在另一列中通过访问它。

获取 “Pigeon”的索引 使用获取相应的列值会做。

1 个答案:

答案 0 :(得分:3)

使用loc

所以对你来说:

df.loc[df.Name == 'Pigeon', 'Category'] 

会给你你想要的东西

示例:

In [17]:

import io
import pandas as pd
temp = """Type      Name           Category              
Bird      Flappy_Bird    Air      
Bird      Pigeon         Air    
Pokemon   Jerry          Aquatic      
Pokemon   Mudkip         Aquatic
Animal    Lion           Terrestrial"""

df = pd.read_csv(io.StringIO(temp), sep='\s+')
df
Out[17]:
      Type         Name     Category
0     Bird  Flappy_Bird          Air
1     Bird       Pigeon          Air
2  Pokemon        Jerry      Aquatic
3  Pokemon       Mudkip      Aquatic
4   Animal         Lion  Terrestrial

[5 rows x 3 columns]
In [19]:

df.loc[df.Name == 'Pigeon','Category']
Out[19]:
1    Air
Name: Category, dtype: object

如果您有多个值而只想要第一个,那么请使用idxmin

In [24]:

df.ix[(df.Name == 'Pigeon').idxmin(),'Category']
Out[24]:
'Air'

修改

因此,对于我们有多个值且您想要访问各个值的情况,您可以检查索引值并直接访问它们:

在[23]中:

df.loc[df.Name=='Pigeon','Category'].index.values
Out[23]:
array([1, 5], dtype=int64)
In [26]:

df.loc[df.Name=='Pigeon','Category'][5]
Out[26]:
'Air2'

如果你想循环它们,那么系列有一个iteritems()方法:

In [28]:

df.loc[df.Name=='Pigeon','Category'].iteritems()
Out[28]:
[(1, 'Air'), (5, 'Air2')]

其中任何一项都应满足您的要求