np.array creation: unexpected behaviour

Hi,
I just came across this unexpected behaviour when creating a np.array() from two other np.arrays of different shape. Have a look at this example: ---- import numpy as np a = np.zeros(3) b = np.zeros((2,3)) c = np.zeros((3,2)) ab = np.array([a, b]) print ab.shape, ab.dtype ac = np.array([a, c], dtype=np.object) print ac.shape, ac.dtype ac_no_dtype = np.array([a, c]) print ac_no_dtype.shape, ac_no_dtype.dtype ---- The output, with NumPy v1.6.1 (Ubuntu 12.04) is: ---- (2,) object (2, 3) object Traceback (most recent call last): File "/tmp/numpy_bug.py", line 9, in <module> ac_no_dtype = np.array([a, c]) ValueError: setting an array element with a sequence. ----
The result for 'ab' is what I expect. The one for 'ac' is a bit surprising. The one for ac_no_dtype even is more surprising.
Is this an expected behaviour?
Best,
Emanuele

On Fri, Jan 24, 2014 at 11:30 AM, Emanuele Olivetti emanuele@relativita.com wrote:
Hi,
I just came across this unexpected behaviour when creating a np.array() from two other np.arrays of different shape. Have a look at this example:
import numpy as np a = np.zeros(3) b = np.zeros((2,3)) c = np.zeros((3,2)) ab = np.array([a, b]) print ab.shape, ab.dtype ac = np.array([a, c], dtype=np.object) print ac.shape, ac.dtype ac_no_dtype = np.array([a, c]) print ac_no_dtype.shape, ac_no_dtype.dtype
The output, with NumPy v1.6.1 (Ubuntu 12.04) is:
(2,) object (2, 3) object Traceback (most recent call last): File "/tmp/numpy_bug.py", line 9, in <module> ac_no_dtype = np.array([a, c]) ValueError: setting an array element with a sequence.
The result for 'ab' is what I expect. The one for 'ac' is a bit surprising. The one for ac_no_dtype even is more surprising.
Is this an expected behaviour?
the exception in ac_no_dtype is what I always expected, since it's not a rectangular array. It usually happened when I make a mistake. **Unfortunately** in newer numpy version it will also create an object array.
AFAIR
Josef
Best,
Emanuele
NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion

On Fri, 24 Jan 2014 17:30:33 +0100, Emanuele Olivetti wrote:
I just came across this unexpected behaviour when creating a np.array() from two other np.arrays of different shape.
The tuple parsing for the construction of new numpy arrays is pretty tricky/hairy, and doesn't always do exactly what you'd expect.
The easiest workaround is probably to pre-allocate the array:
In [24]: data = [a, c] In [25]: x = np.empty(len(data), dtype=object) In [26]: x[:] = data In [27]: x.shape Out[27]: (2,)
Regards Stéfan
participants (3)
-
Emanuele Olivetti
-
josef.pktd@gmail.com
-
Stéfan van der Walt