jhp - 1 month ago 4x

Python Question

This is my very first question. So let's see if I can explain exactly what I need.

I am given a python

`list`

`my_list = [`

np.ones((20, 3, 3)),

np.ones(( 1, 3, 3)),

np.ones((20, 3, 3))

]

Now when I do

`wrapped_list = np.array(my_list)`

I get an object of the following structure

`np.array(shape=(3, ), dtype=object)`

with the initial three arrays as content. This is what I want. Now the problem:

If

`my_list`

`my_list2 = [`

np.ones((20, 3, 3)),

np.ones((20, 3, 3)),

np.ones((20, 3, 3))

]

np.array(my_list2)

leads to

`np.array(shape=(3, 20, 3, 3), dtype=np.float64)`

This is

`dtype`

`np.array(my_list, dtype=object)`

which will cast

`dtype=object`

I think I found a way to go without wrapping at all, but I am curious on how to set the dtype on a np.array without affecting nested numpy arrays.

Answer

Create an empty object arrary first and fill it with my_list, e.g.:

```
wrapped_list = np.empty((3,),dtype=object)
wrapped_list[:] = my_list2
```

Source (Stackoverflow)

Comments