简体   繁体   English

Python Numpy:从数组中提取一行

[英]Python Numpy: Extracting a row from an array

I'm trying to extract a row from a Numpy array using 我正在尝试使用以下方法从Numpy数组中提取一行

t = T[153,:]

But I'm finding that where the size of T is (17576, 31), the size of t is (31,) - the dimensions don't match! 但是我发现T的大小是(17576,31), t的大小是(31,)-尺寸不匹配!

I need t to have the dimensions (,31) or (1,31) so that I can input it into my function. 我需要t有尺寸(31)或(1,31),这样我可以输入到我的功能。 I've tried taking the transpose, but that didn't work. 我已经尝试过移调,但是那没有用。

Can anyone help me with what should be a simple problem? 谁能帮助我解决一个简单的问题?

Many thanks 非常感谢

You can extract the row with a slice notation: 您可以使用切片符号提取行:

t = T[153:154,:]    # will extract row 153 as a 2d array

Example : 范例

T = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])

T[1,:]
# array([5, 6, 7, 8])

T[1,:].shape
# (4,)

T[1:2,:]
# array([[5, 6, 7, 8]])

T[1:2,:].shape
# (1, 4)

Although this might seem surprising, it's actually 100% idiomatic. 尽管这似乎令人惊讶,但实际上是100%惯用的。 Think about what you get when you index a list in Python, and what you get when you slice a list: 考虑一下在Python中为列表建立索引时会得到什么,以及在对列表进行切片时会得到什么:

>>> l = list(range(10))
>>> l[4]
4
>>> l[4:5]
[4]

Of course we see the same thing in an ordinary 1-d array: 当然,我们在普通的1维数组中会看到相同的结果:

>>> a = numpy.arange(10)
>>> a[4]
4
>>> a[4:5]
array([4])

And so it stands to reason that we'd see the same thing in a 2-d array as well: 因此,我们有理由在二维数组中也看到相同的东西:

>>> a = numpy.arange(25).reshape(5, 5)
>>> a[4]
array([20, 21, 22, 23, 24])
>>> a[4:5]
array([[20, 21, 22, 23, 24]])

The shapes reflect this difference: 形状反映了这种差异:

>>> a[4].shape
(5,)
>>> a[4:5].shape
(1, 5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM