1

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

I am given a python list of numpy arrays which can or cannot have different lengths (in one dimension only but this is not important here), e.g.

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 contained sublists of identical length, then I get, e.g.

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 not, what I want. I tried specifying the dtype, like

np.array(my_list, dtype=object) 

which will cast all (sub-)arrays to 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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this does what I want although I tried to put this into a one-liner in a lambda function actually. Is there a way to do that, too?
The right way to avoid long code is to wrap it in function definition. Don't try to use lambda to combine lines.
0

Another (dumb) way, that at least has the virtue of being a single expression:

wrapped_list = np.array(my_list + [None])[:-1]

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.