Numpy 2D阵列切片每行的不同元素

发布于 2025-02-06 08:18:22 字数 202 浏览 3 评论 0原文

假设我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深海蓝天 2025-02-13 08:18:23

您可以通过:创建两个单独的1D数组,

a[0][:3], a[1][:2]

但是您不能用两个不同尺寸的1D数组制作2D数组。请注意,Numpy中的数组是矩阵,而不是诸如Python列表的2D列表。

另一方面,您可以得到不同的切片,但每行的大小相同,并将它们作为2D数组。例如,假设您具有以下2D数组:

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

现在您可以从第一行中选择三个元素,第二行中的三个元素,但处于不同的位置:

a[0][:3], a[1][2:5]

然后您可以组合它们以制作新的2D数组:

np.vstack((a[0][:3], a[1][2:5]))

结果将是:

array([[ 1,  2,  3],
       [ 8,  9, 10]])

如果要替换列和行,则可以使用transposet

np.vstack((a[0][:3], a[1][2:5])).T

那么您

array([[ 1,  8],
       [ 2,  9],
       [ 3, 10]])
  • 也可以 使用:这两个阵列的组合:
np.hstack((a[0][:3], a[1][2:5]))

结果是:

array([ 1,  2,  3,  8,  9, 10])

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. 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:

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:

np.vstack((a[0][:3], a[1][2:5])).T

Then you have:

array([[ 1,  8],
       [ 2,  9],
       [ 3, 10]])
  • You also can make a new 1D array with the combination of these two arrays:
np.hstack((a[0][:3], a[1][2:5]))

And result is:

array([ 1,  2,  3,  8,  9, 10])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文