2017-07-02 86 views
1

我有熊貓數據結構,這是我創建這樣的:類型錯誤:unhashable類型: '切片' 的熊貓

test_inputs = pd.read_csv("../input/test.csv", delimiter=',') 

其形狀

print(test_inputs.shape) 

是本

(28000, 784) 

我想打印其行的子集,如下所示:

print(test_inputs[100:200, :]) 
print(test_inputs[100:200, :].shape) 

但是,我得到:

TypeError: unhashable type: 'slice' 

任何想法可能是錯誤的?

+1

'test_inputs [100:200]'或'test_inputs.loc [100:200,:]​​'? – MaxU

回答

2

還有更多可能的解決方案,但輸出不相同:

loc選擇由標籤,但iloc和切片沒有功能,起始邊界時包括,而上限是排除docs - select by positions

test_inputs = pd.DataFrame(np.random.randint(10, size=(28, 7))) 

print(test_inputs.loc[10:20]) 
    0 1 2 3 4 5 6 
10 3 2 0 6 6 0 0 
11 5 0 2 4 1 5 2 
12 5 3 5 4 1 3 5 
13 9 5 6 6 5 0 1 
14 7 0 7 4 2 2 5 
15 2 4 3 3 7 2 3 
16 8 9 6 0 5 3 4 
17 1 1 0 7 2 7 7 
18 1 2 2 3 5 8 7 
19 5 1 1 0 1 8 9 
20 3 6 7 3 9 7 1 

print(test_inputs.iloc[10:20]) 
    0 1 2 3 4 5 6 
10 3 2 0 6 6 0 0 
11 5 0 2 4 1 5 2 
12 5 3 5 4 1 3 5 
13 9 5 6 6 5 0 1 
14 7 0 7 4 2 2 5 
15 2 4 3 3 7 2 3 
16 8 9 6 0 5 3 4 
17 1 1 0 7 2 7 7 
18 1 2 2 3 5 8 7 
19 5 1 1 0 1 8 9 

print(test_inputs[10:20]) 
    0 1 2 3 4 5 6 
10 3 2 0 6 6 0 0 
11 5 0 2 4 1 5 2 
12 5 3 5 4 1 3 5 
13 9 5 6 6 5 0 1 
14 7 0 7 4 2 2 5 
15 2 4 3 3 7 2 3 
16 8 9 6 0 5 3 4 
17 1 1 0 7 2 7 7 
18 1 2 2 3 5 8 7 
19 5 1 1 0 1 8 9 
2

熊貓索引真的很混亂,因爲它看起來像列表索引,但事實並非如此。您需要使用.iloc,這是由位置索引

print(test_inputs.iloc[100:200, :]) 

如果你不使用列選擇,你可以省略

print(test_inputs.iloc[100:200]) 

附:使用.loc不是你想要的,因爲它看起來不是行號,而是行索引,試圖找到索引值100和200,並且會給你之間的界限。如果您剛剛創建了DataFrame .iloc.loc可能會給出相同的結果,但在這種情況下使用.loc是非常糟糕的做法,因爲它會導致您難以理解索引因某種原因而發生更改的問題(例如,您會選擇一些行的子集,從那一刻起行號和索引不會相同)。