0

Anybody know how I can "unpack" lists which are elements/cells of a np.array? This is what the output looks like now:

[[0 301227 0.863 0.456 -3.551 0.532 135.96200000000002 4
  list([0.49, 0.33, 0.33, 0.28, 0.26, 0.47, 0.28, 0.29, 0.41, 0.42, 0.85, 0.48])
  list([53.09, 119.1, 36.67, -1.91, 11.38, -20.86, -0.56, 4.01, -3.51, 0.9, -8.72, 1.04])
  66.66666666666667 1.0]]

I want to unpack those lists so that each value is just another item/column in my array. I can also make the lists into np.arrays if that helps. Should be an easy fix, I just haven't found it yet.

Cheers

1

2 Answers 2

1

I think I understand your issue a little better now. I created something to try and match the situation you're facing, and it returns a list where every item inside every list becomes just another item as you wanted:

import numpy as np

input_list = [0, 2, 4, 1, 5,np.array([1, 2, 3]), 6, 1, 6, 1, 2, np.array([1, 2, 3])] 

def flatten(l):
    for item in l:
        try:
            yield from flatten(item)
        except TypeError:
            yield item

output_list = list(flatten(input_list)))

Output is: [0, 2, 4, 1, 5, 1, 2, 3, 6, 1, 6, 1, 2, 1, 2, 3]

Tested it with np arrays and list as well, should have no problems. Also, I didn't create the output list as a np.array, but you can easily change it to do so if you wish

Sign up to request clarification or add additional context in comments.

2 Comments

Quite elegant little hack you have there! It works really well. I'm now feeding individual rows of my original array to it, then re-assembling the rows later on in a NumPy array.
Thank you! I just found a question that has a problem similar to yours, code similar to mine and other hacks that might have better performance! stackoverflow.com/questions/2158395/…
0

If I understood your question correctly, you can use numpy.concatenate() for that:

list = np.concatenate(input_list).ravel()

If you want the output to be in list form, you can append .tolist()

2 Comments

Ah yes! It works when appending .tolist() . Thanks!
However, it doesn't unpack the lists it only makes the np.array structure a list. So it doesn't actually solve my problem. There are still lists within the list.

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.