ravi
ravi

Reputation: 6328

creating numpy 2D array from list of numpy 1D array

I am facing an abnormal behavior of numpy array, while trying to create numpy 2D array from some numpy array. Below is the sample code-

x = []
x.append(x1)
x.append(x2)
x.append(x3)
x = np.array(x)

print x1.shape, type(x1)
print x2.shape, type(x2)
print x3.shape, type(x3)
print  x.shape, type(x)
print x[0].shape, type(x[0])

(1318,) <type 'numpy.ndarray'>
(1352,) <type 'numpy.ndarray'>
(1286,) <type 'numpy.ndarray'>
(3,) <type 'numpy.ndarray'>
(1318,) <type 'numpy.ndarray'>

I wasn't expecting for this output. Hence I tired another code, which looks like below-

x1 = np.arange(4)
x2 = np.arange(4,8)
x3 = np.arange(8,12)
x.append(x1)
x.append(x2)
x.append(x3)
x = np.array(x)

print x.shape
(3, 4)

Why, I am not seeing 2d array in first case?

Upvotes: 2

Views: 225

Answers (1)

miradulo
miradulo

Reputation: 29680

If the length of each array were equal, you would indeed see the 2d shape you were expecting - as you mentioned in a comment you should resample accordingly.


Your currently constructed "jagged array" of arrays would have to be treated similarly to a regular Python list, and does not support nice things like .sum().

With a similarly jagged array

>>> x.sum()
ValueError: operands could not be broadcast together with shapes (4,) (3,) 

This lack of support for jagged arrays is because NumPy is optimized for arrays of numbers with a fixed dimension.

Upvotes: 1

Related Questions