为什么这两个Numpy Slice命令的输出类型会有所不同 [英] why there is deference between the output type of this two Numpy slice commands

查看:18
本文介绍了为什么这两个Numpy Slice命令的输出类型会有所不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面两个命令的输出给出了不同的数组形状,我非常感谢解释原因并向我推荐参考资料(如果有),我在互联网上搜索了一下,但没有找到任何明确的解释。

data.shape
(11,2)

# outputs the values in column-0 in an (1x11) array.
data[:,0] 

array([-7.24070e-01, -2.40724e+00,  2.64837e+00,  3.60920e-01,
        6.73120e-01, -4.54600e-01,  2.20168e+00,  1.15605e+00,
        5.06940e-01, -8.59520e-01, -5.99700e-01])


# outputs the values in column-0 in an (11x1) array
data[:,:-1] 


array([[-7.24070e-01],
       [-2.40724e+00],
       [ 2.64837e+00],
       [ 3.60920e-01],
       [ 6.73120e-01],
       [-4.54600e-01],
       [ 2.20168e+00],
       [ 1.15605e+00],
       [ 5.06940e-01],
       [-8.59520e-01],
       [-5.99700e-01]])

推荐答案

我会尝试将评论合并为答案。

首先了解一下Python列表索引

In [92]: alist = [1,2,3]

选择项目:

In [93]: alist[0]
Out[93]: 1

复制整个列表:

In [94]: alist[:]
Out[94]: [1, 2, 3]

或长度为2、1或0的切片:

In [95]: alist[:2]
Out[95]: [1, 2]
In [96]: alist[:1]
Out[96]: [1]
In [97]: alist[:0]
Out[97]: []

数组遵循相同的基本规则

In [98]: x = np.arange(12).reshape(3,4)
In [99]: x
Out[99]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

选择一行:

In [100]: x[0]
Out[100]: array([0, 1, 2, 3])

或列:

In [101]: x[:,0]
Out[101]: array([0, 4, 8])

x[0,1]选择单个元素。

https://numpy.org/doc/stable/user/basics.indexing.html#single-element-indexing

使用切片编制索引将返回多行:

In [103]: x[0:2]
Out[103]: 
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
In [104]: x[0:1]            # it retains the dimensions, even if only 1 (or even 0)
Out[104]: array([[0, 1, 2, 3]])

列也是如此:

In [106]: x[:,0:1]
Out[106]: 
array([[0],
       [4],
       [8]])

两个维度的子切片:

In [107]: x[0:2,1:3]
Out[107]: 
array([[1, 2],
       [5, 6]])

https://numpy.org/doc/stable/user/basics.indexing.html

x[[0]]也返回二维数组,但这会进入";Advanced";索引(它没有等效列表)。

这篇关于为什么这两个Numpy Slice命令的输出类型会有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆