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?

deepAgrawal
  • 673
  • 1
  • 7
  • 25

1 Answers1

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])
jtwalters
  • 1,024
  • 7
  • 25