Numpy 2D阵列切片每行的不同元素
假设我有一个2D numpy数组,
a= [[1,2,3]
[4,5,6]]
我可以将其切成薄片以选择每行2个元素:
a[:,0:2]
Output:
[[1,2]
[4,5]]
但是我如何单独切成不同的行,例如第一行的3个元素,第二行元素是两个元素
Lets say i have a 2D numpy array
a= [[1,2,3]
[4,5,6]]
i can slice it to select 2 elements form each row:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过:创建两个单独的1D数组,
但是您不能用两个不同尺寸的1D数组制作
2D数组
。请注意,Numpy中的数组是矩阵,而不是诸如Python列表的2D列表。另一方面,您可以得到不同的切片,但每行的大小相同,并将它们作为2D数组。例如,假设您具有以下2D数组:
现在您可以从第一行中选择三个元素,第二行中的三个元素,但处于不同的位置:
然后您可以组合它们以制作新的2D数组:
结果将是:
如果要替换列和行,则可以使用
transpose
或t
:那么您
结果是:
You can create two separate 1D arrays by:
But you cannot make a
2D array
with two 1D arrays of different sizes. Note that arrays in numpy are matrices, not 2D lists like Python lists.On the other hand, you can get a different slice but the same size of each row and make them as a 2D array. For example, assume you have the following 2D array:
Now you can select, for example, three elements from the 1st row and three elements from the 2nd row but in a different position:
Then you can combine them to make a new 2D array:
And the result would be:
And if you want to replace columns and rows you can use
transpose
orT
:Then you have:
And result is: