I have a list of ten 1-dimension-ndarrays, where each on hold a string, and I would like to one long list where every item will be a string (without using ndarrays anymore). How should I implement it?
3 Answers
I think you need convert to array first, then flatten by ravel and last convert to list:
a = [np.array([x]) for x in list('abcdefghij')]
print (a)
[array(['a'],
dtype='<U1'), array(['b'],
dtype='<U1'), array(['c'],
dtype='<U1'), array(['d'],
dtype='<U1'), array(['e'],
dtype='<U1'), array(['f'],
dtype='<U1'), array(['g'],
dtype='<U1'), array(['h'],
dtype='<U1'), array(['i'],
dtype='<U1'), array(['j'],
dtype='<U1')]
b = np.array(a).ravel().tolist()
print (b)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Another solution with flattenting by chain.from_iterable:
from itertools import chain
b = list(chain.from_iterable(a))
print (b)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Comments
I found a code that accomplishes my request: x = [str(i[0]) for i in the_list]
1 Comment
str?A good general purpose way of 'flattening' out the inner arrays of a list (or object dtype array of arrays) is to use one of the concatenate functions.
For example with a list that contains arrays of different lengths, including a 0d one):
In [600]: ll = [np.array('one'), np.array(['two','three']),np.array(['four'])]
In [601]: ll
Out[601]:
[array('one',
dtype='<U3'), array(['two', 'three'],
dtype='<U5'), array(['four'],
dtype='<U4')]
In [602]: np.hstack(ll).tolist()
Out[602]: ['one', 'two', 'three', 'four']
In [603]: np.hstack(ll).tolist()
Out[603]: ['one', 'two', 'three', 'four']
I had to use hstack because I included a 0d array; if they'd all been 1d concatenate would be enough.
If the arrays all contain one string, then the other solutions work fine
In [608]: ll = [np.array(['one']), np.array(['two']),np.array(['three']),np.array(['four'])]
In [609]: ll
Out[609]:
[array(['one'],
dtype='<U3'), array(['two'],
dtype='<U3'), array(['three'],
dtype='<U5'), array(['four'],
dtype='<U4')]
In [610]: np.hstack(ll).tolist()
Out[610]: ['one', 'two', 'three', 'four']
In [611]: np.array(ll)
Out[611]:
array([['one'],
['two'],
['three'],
['four']],
dtype='<U5') # a 2d array which can be raveled to 1d
In [612]: [i[0] for i in ll] # extracting the one element from each array
Out[612]: ['one', 'two', 'three', 'four']