How can i construct a numpy one dimension array of lists
np.array([[1,2,3], [4,5,6]], dtype=np.object)
will create a numpy array of (2,3) while i want it to be a one dimension (2, )
for example if the list where unequal
np.array([[1,2,3], [4,5]], dtype=np.object)
it would result in a one dimension (2, )
i understand that numpy is trying to optimize the types and space but i need to force it to be one dimension
i can do this
arr = np.empty(2, dtype=object)
arr[0] = [1, 2, 3]
arr[1] = [1, 2, 4]
But it is ugly, is there a better way?
CodePudding user response:
In [16]: arr = np.empty(2, dtype=object)
...: arr[0] = [1, 2, 3]
...: arr[1] = [1, 2, 4]
In [17]: arr
Out[17]: array([list([1, 2, 3]), list([1, 2, 4])], dtype=object)
You can assign both lists at once:
In [18]: arr = np.empty(2, dtype=object)
...: arr[:] = [[1, 2, 3],[1, 2, 4]]
In [19]: arr
Out[19]: array([list([1, 2, 3]), list([1, 2, 4])], dtype=object)
Create and fill is the most reliable way of creating an object dtype array. Otherwise you are at the mercy of the complex np.array
function. The primary purpose of that function is to make multidimensional numeric dtype arrays. These object dtype arrays are fall back option, one which it only uses when it can't make a "proper" numpy array.
Simply specifying object
dtype does not tell it the desired "depth" of the array. (2,) and (2,3) are equally valid shapes given that nested list. Default is the multidimensional one.
Remember, an object dtype array is basically a list, with few, if any, advantages.