2

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?

2
  • 1
    What shape were you hoping the first array to be? The length of each component is not equal. Commented Jan 19, 2017 at 14:19
  • wtf!!! I got it. I need to resample all the data first.... Commented Jan 19, 2017 at 14:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.