我有一个熊猫数据结构,我这样创建:
test_inputs = pd.read_csv("../input/test.csv", delimiter=',')
Run Code Online (Sandbox Code Playgroud)
它的形状
print(test_inputs.shape)
Run Code Online (Sandbox Code Playgroud)
这是
(28000, 784)
Run Code Online (Sandbox Code Playgroud)
我想打印其行的子集,如下所示:
print(test_inputs[100:200, :])
print(test_inputs[100:200, :].shape)
Run Code Online (Sandbox Code Playgroud)
但是,我得到了:
TypeError: unhashable type: 'slice'
Run Code Online (Sandbox Code Playgroud)
知道什么可能是错的吗?
大熊猫中的索引真的令人困惑,因为它看起来像列表索引,但事实并非如此.你需要使用.iloc
,这是按位置索引
print(test_inputs.iloc[100:200, :])
Run Code Online (Sandbox Code Playgroud)
如果您不使用列选择,则可以省略它
print(test_inputs.iloc[100:200])
Run Code Online (Sandbox Code Playgroud)
PS使用.loc
不是你想要的,因为它看起来不是行号,而是行索引,试图找到索引值100和200,并给你两者之间的界限.如果您刚刚创建了DataFrame []
并且.loc
可能会给出相同的结果,但.iloc
在这种情况下使用是一种非常糟糕的做法,因为当索引因某种原因发生变化时会导致难以理解的问题(例如,您将选择一些子集行,从那一刻起,行号和索引将不相同).
有更多可能的解决方案,但输出并不相同:
loc
通过标签选择,但iloc
并没有切片功能,起动界限被包括,而上限是排除,文档-由位置选择:
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28733 次 |
最近记录: |