0

I have 2 single-dimensional NumPy arrays

a = np.array([0, 4])
b = np.array([3, 2])

I want to create a 2d array of numbers

c = np.array([[0,1,2], [4,5]])

I can also create this using a for loop

EDIT: Updating loop based on @jtwalters comments

c = np.zeros(b.shape[0], dtype=object)
for i in range(b.shape[0]):
    c[i] = np.arange(a[i], a[i]+b[i])

How can I achieve this via vectorization/broadcasting?

7
  • [[0,1,2], [4,5]] cannot be made into a 2d array. Commented Jul 12, 2021 at 7:21
  • Does np.arange(6).reshape(2,3) work for you? Commented Jul 12, 2021 at 7:24
  • I agree with your first comment. But np.arange(6).reshape(2,3) won't work. 2 rows should be np.arange(a[i], a[i]+b[i]) please note that 3 is not in my resulting array. Commented Jul 12, 2021 at 7:26
  • I was trying make sense out of a confusing example. Commented Jul 12, 2021 at 7:37
  • Your loop does not work. Commented Jul 12, 2021 at 10:16

1 Answer 1

1

To create an ndarray from ragged nested sequences you must put dtype=object.

For example:

c = np.empty(b.shape[0], dtype=object)
for i in range(b.shape[0]):
    c[i] = np.arange(a[i], a[i]+b[i])

Or with array for:

np.array([np.arange(a[i], a[i]+b[i]) for i in range(b.shape[0])], dtype=object)

Vectorized:

def func(a, b):
  return np.arange(a, a + b)

vfunc = np.vectorize(func, otypes=["object"])
vfunc([0, 4], [3, 2])
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to vectorize this?
@deepAgrawal Yes, I update the code with np.vectorize

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.