0

I have an array that looks like this:

[list([130365]) list([80476]) list([999078, 999078]) list([86833, 86833])
 list([63767, 63767]) list([63777, 63777]) list([830166, 830166])]

>>> type(results)
<class 'numpy.ndarray'>

And I want to transform it into an array containing just the items:

[130365 80476 999078 86833 86833 63767 63767 63777 63777 830166 830166]

Everything I've tried so far didn't work, how can I do this?

Sara Kerrigan
  • 185
  • 1
  • 13
  • Does [this](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) solve your problem? – Lukas Thaler Mar 06 '20 at 10:59
  • 2
    Does this answer your question? [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – Lukas Thaler Mar 06 '20 at 10:59

2 Answers2

2

I see that you have a nested NumPy array. I've reproduced your problem.

import numpy as np
results = np.array([[130365], [80476], [999078, 999078], [86833, 86833] , [63767, 63767], [63777, 63777], [830166, 830166]])

enter image description here

For this problem, you can use NumPy's concatenate:

results_flat = np.concatenate(results)

enter image description here

Notes:
1. To make sure that the array is one-dimensional (i.e., "flattened"), you can use this:

results_flat = np.concatenate(results).ravel()

In your case, this and the method above yield the same results.

enter image description here


2. If you want a list:

results_flat = np.concatenate(results).tolist()

enter image description here

Dharman
  • 30,962
  • 25
  • 85
  • 135
JP Maulion
  • 2,454
  • 1
  • 10
  • 13
1

You can simply use the from_iterable function:

import itertools
import numpy as np

results = np.array([list([130365]), list([80476]), list([999078, 999078]),
                    list([86833, 86833]), list([63767, 63767]),
                    list([63777, 63777]), list([830166, 830166])])

flat_results = np.array(list(itertools.chain.from_iterable(results)))
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50