[英]Numpy 2d Array slicing different elements from each row
Lets say i have a 2D numpy array假设我有一个 2D numpy 数组
a= [[1,2,3]
[4,5,6]]
i can slice it to select 2 elements form each row:我可以将其切片以从每行中选择 2 个元素:
a[:,0:2]
Output:
[[1,2]
[4,5]]
but how can i slice different rows individually with different lengths, like 3 elements from first row and two from second但是我如何才能以不同的长度单独切片不同的行,例如第一行的 3 个元素和第二行的两个元素
You can create two separate 1D arrays by:您可以通过以下方式创建两个单独的一维数组:
a[0][:3], a[1][:2]
But you cannot make a 2D array
with two 1D arrays of different sizes.但是你不能用两个不同大小的一维数组制作一个2D array
。 Note that arrays in numpy are matrices, not 2D lists like Python lists.请注意,numpy 中的数组是矩阵,而不是像 Python 列表那样的二维列表。
On the other hand, you can get a different slice but the same size of each row and make them as a 2D array.另一方面,您可以获得不同的切片,但每行的大小相同,并将它们制作为 2D 数组。 For example, assume you have the following 2D array:例如,假设您有以下二维数组:
a = np.array([[1, 2, 3, 4, 5],[6, 7, 8, 9, 10]])
Now you can select, for example, three elements from the 1st row and three elements from the 2nd row but in a different position:例如,现在您可以选择第一行中的三个元素和第二行中的三个元素,但位置不同:
a[0][:3], a[1][2:5]
Then you can combine them to make a new 2D array:然后你可以将它们组合成一个新的二维数组:
np.vstack((a[0][:3], a[1][2:5]))
And the result would be:结果将是:
array([[ 1, 2, 3],
[ 8, 9, 10]])
And if you want to replace columns and rows you can use transpose
or T
:如果要替换列和行,可以使用transpose
或T
:
np.vstack((a[0][:3], a[1][2:5])).T
Then you have:然后你有:
array([[ 1, 8],
[ 2, 9],
[ 3, 10]])
np.hstack((a[0][:3], a[1][2:5]))
And result is:结果是:
array([ 1, 2, 3, 8, 9, 10])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.