2016-10-21 29 views
2
CD_FARE MTH DAY ID_CALENDAR H0 H1 H2 H3 PE1 PE2 PE3 PE4 
2.0  1 M Cal01  1  2 1 3 0.14 0.15 0.1 0.2 
2.0  1 T Cal01  1  2 1 3 0.14 0.16 0.1 0.2 
2.0  1 W Cal01  1  2 4 3 0.14 0.12 0.1 0.2 
2.0  1 T Cal01  2  2 1 3 0.14 0.11* 0.1 0.2 
2.0  1 F Cal01  4  2 1 3 0.14 0.18 0.1 0.2 

我想知道如何從特定單元格獲取值。按行和列獲取單元格的值

例如:我想返回值0.11。 我知道該行的位置(在這種情況下爲3)以及該列的名稱(PE2)。 我可以選擇這種方式?:

data = df.iloc[3, 'PE2'] 

回答

2

顯然,這是行不通的數據,它提供了一個ValueError

ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types 

但是如果你使用df.loc[3, 'PE2']代替iloc方法,它的工作原理

0

如果需要按位置選擇需要Series.iloc

print (df['PE2'].iloc[3]) 
0.11 

樣品:

df = pd.DataFrame({'PE2':[1,2,3], 
        'B':[4,5,6]}, index=['a','b','c']) 

print (df) 
    B PE2 
a 4 1 
b 5 2 
c 6 3 

#third row in colum PE2 
print (df['PE2'].iloc[2]) 
3 

#index value c and column PE2 
print (df.ix['c','PE2']) 
3 

#index value c and column PE2 
print (df.loc['c','PE2']) 
3 

#third row and second column 
print (df.iloc[2,1]) 
3 

但如果需要通過索引和列值使用ixDataFrame.loc選擇:

df = pd.DataFrame({'PE2':[1,2,3], 
        'B':[4,5,6]}) 

print (df) 
    B PE2 
0 4 1 
1 5 2 
2 6 3 

print (df.loc[2, 'PE2']) 
3 

print (df.ix[2, 'PE2']) 
3 

您還可以檢查selection by labelselection by positionpandas documentation