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

Alex
  • 65
  • 8
  • 2
    Welcome to StackOverflow! Please take the time to read this post on how to [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) as well as how to provide a [minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and revise your question accordingly – yatu Sep 09 '20 at 14:17

2 Answers2

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

  • 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. – Alex Sep 09 '20 at 15:16
  • 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! https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists – Guilherme Freitas Sep 09 '20 at 15:19
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()

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    Ah yes! It works when appending ```.tolist()``` . Thanks! – Alex Sep 09 '20 at 14:40
  • 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. – Alex Sep 09 '20 at 14:52