0

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?

5
  • If you don't want (2,3), why not create a list of sublists directly? Commented Dec 6, 2021 at 8:00
  • ugly is in the eye of the beholder. If you don't like it, hide it in a function wrapper :) Commented Dec 6, 2021 at 8:04
  • @meTchaikovsky, not my choice have to use numpy Commented Dec 6, 2021 at 9:15
  • Thanks @hpaulj , i thought there was some numpy builtin option Commented Dec 6, 2021 at 9:15
  • It is not clear what are you really trying to achieve? It seems like you are using the library wrong. Commented Dec 6, 2021 at 12:20

1 Answer 1

1
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.

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.