BOUNCE
BOUNCE

Reputation: 167

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

Given an x-dataset,

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

Upvotes: 2

Views: 270

Answers (1)

kmario23
kmario23

Reputation: 61355

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. For the column size we simply take the length from the x array. For reasonably larger arrays, this approach would be the fastest.

Upvotes: 1

Related Questions