简体   繁体   English

给定一维和一个常数,有效地创建二维 numpy 数组

[英]Efficiently create 2d numpy array given 1 dimension and a constant

Given an x-dataset,给定一个 x 数据集,

x = np.array([1, 2, 3, 4, 5])

what is the most efficient way to create the NumPy array where each x coordinate is paired with a y-coordinate of value 0?创建 NumPy 数组的最有效方法是什么,其中每个 x 坐标都与值为 0 的 y 坐标配对? I am wondering if there is a way specifically that doesn't require any hard coding, so that x could vary in length without causing failure.我想知道是否有一种专门不需要任何硬编码的方法,以便 x 可以改变长度而不会导致失败。

As per your problem statement, the following is one way to do it.根据您的问题陈述,以下是一种方法。

# initialize an array of zeros
In [36]: res = np.zeros((2, *x.shape), dtype=x.dtype)

# fill `x` as first row
In [37]: res[0] = x

In [38]: res
Out[38]: 
array([[1, 2, 3, 4],
       [0, 0, 0, 0]])

When we initialize the array of zeros, we use 2 for axis-0 dimension since your requirement is to create a 2D array.当我们初始化零数组时,我们使用 2 作为轴 0 维度,因为您的要求是创建一个二维数组。 For the column size we simply take the length from the x array.对于列大小,我们只需从x数组中获取长度。 For reasonably larger arrays, this approach would be the fastest.对于相当大的 arrays,这种方法是最快的。

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

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