2014-05-06 88 views
0

我有一個數據幀如下:訪問另一列按值,熊貓

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

對於喜歡說"Pigeon"給定的名字,我需要在類別欄訪問相應的價值,即它應該給我的字符串"Air"
我有2個值Pigeon,但我需要返回「空氣」的第二個觀察。

請注意,我是根本沒有使用索引,所以有第二個觀察與iloc不會做的事情。我需要通過價值在另一列訪問它。

或者類似的東西獲得指數「鴿子」使用得到相應的列值就行了。

+0

不知道你的「不使用索引」的評論,因爲施工的每個數據幀都有一個索引...它是不可能有一個沒有。在這種情況下,不'df [df.Name =='Pigeon']。類別'工作嗎? – cwharland

+0

其實這樣做會更好,獲得當前「Pigeon」的索引並使用該索引在「類別」 –

+0

@cwharland中獲得相應的值您的解決方案的工作,只是爲索引部分添加一個條件並將其框架在一個答案中..: ) –

回答

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')] 

任一應滿足你的要求

+0

是的當然..更新你的答案。並讓我們清理註釋部分 –