Skip to content

np.asarray - unexpected behaviour #14221

@deviganesan-coder

Description

@deviganesan-coder

When I try to do np.asarray of a list of arrays, it results in different behaviour depending on the dimensions of the arrays. When the list of arrays is of dimensions like (n,n) and (n,) it results in error.

Reproducing code example:

import numpy as np
a1 = [array([[-0.00491985,  0.00491965],
        [-0.00334969,  0.00334955],
        [-0.00136081,  0.00136076]], dtype=float32),
 array([-0.00104678,  0.00104674], dtype=float32)]

a2 = [array([[-0.00334969,  0.00334955],
        [-0.00136081,  0.00136076]], dtype=float32),
 array([-0.00104678,  0.00104674], dtype=float32)]

print(np.asarray(a1))   #works fine
print(np.asarray(a2))  #throws error
print(np.asarray([a.reshape(-1, 2) for a in a2]))  #works fine

Error message:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-51-3060768e9016> in <module>()
----> 1 np.asarray(a2)

/home/devi/.local/lib/python3.5/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
    536 
    537     """
--> 538     return array(a, dtype, copy=False, order=order)
    539 
    540 

ValueError: could not broadcast input array from shape (2,2) into shape (2)

Numpy/Python version information:

('1.16.3', '2.7.12 (default, Nov 12 2018, 14:36:49) \n[GCC 5.4.0 20160609]')

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions