2016-10-19 40 views

回答

1

它失敗,因爲2:4是無效的語法來訪問鍵/一DF的列:

In [73]: 
df[[2:4]] 
    File "<ipython-input-73-f0f09617b349>", line 1 
    df[[2:4]] 
     ^
SyntaxError: invalid syntax 

這是,如果你沒有定義不同字典,並嘗試相同的語法:

In [74]: 
d = {0:0,1:1,2:2,3:3,4:4,5:5} 
d 

Out[74]: 
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5} 

In [76]: 
d[[2:4]] 

    File "<ipython-input-76-ea5d68adc389>", line 1 
    d[[2:4]] 
     ^
SyntaxError: invalid syntax 

The []語法用於訪問匹配的列標籤,您不能通過列表中的切片訪問像這樣的列的範圍,它需要是您已經找到的值列表

較新的方法如ilocixloc支撐片範圍

什麼爲你工作,初步選定使用的標籤列表中的列:

In [77]: 
df[[2,3,4]] 

Out[77]: 
    2 3 4 
0 3 4 5 
1 3 4 5 
2 3 4 5 
3 3 4 5 
4 3 4 5 

,然後通過切片選擇行:

In [79]: 
df[[2,3,4]][2:4] 

Out[79]: 
    2 3 4 
2 3 4 5 
3 3 4 5 
1

我想你需要ix

print (df.ix[2:4,2:4]) 
    2 3 
2 3 4 
3 3 4 
4 3 4 
+0

很酷,感謝那jezrael –

+0

對不起,我的coleague找到了我。現在我看到第二個答案,我認爲這是非常好的解釋。我認爲最好的選擇是使用['ix'](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html),['iloc'](http ://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html)或['loc'](http://pandas.pydata.org/pandas-docs/stable/generated/ pandas.DataFrame.loc.html)。 – jezrael