2017-07-02 74 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是非常糟糕的做法,因为它会导致您难以理解索引因某种原因而发生更改的问题(例如,您会选择一些行的子集,从那一刻起行号和索引不会相同)。

相关问题