Bol*_*ain 14 python indexing numpy slice
我倾向于用括号来索引numpy数组(矩阵),但我注意到当我想切片数组(矩阵)时我必须使用逗号表示法.为什么是这样?例如,
>>> x = numpy.array([[1, 2], [3, 4], [5, 6]])
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> x[1][1]
4 # expected behavior
>>> x[1,1]
4 # expected behavior
>>> x[:][1]
array([3, 4]) # huh?
>>> x[:,1]
array([2, 4, 6]) # expected behavior
Run Code Online (Sandbox Code Playgroud)
use*_*ica 20
这个:
x[:, 1]
Run Code Online (Sandbox Code Playgroud)
表示" x沿第一轴取所有索引,但沿第二轴取索引1".
这个:
x[:][1]
Run Code Online (Sandbox Code Playgroud)
表示" x沿第一轴取所有索引(所以全部x),然后沿结果的第一轴取索引1 ".你正在应用1错误的轴.
x[1][2]并且x[1, 2]只是等价,因为使用整数索引数组会将所有剩余的轴移向形状的前面,因此第一个轴x[1]是第二个轴x.这根本没有概括; 你应该几乎总是使用逗号而不是多个索引步骤.
| 归档时间: |
|
| 查看次数: |
3566 次 |
| 最近记录: |