How do I convert a NumPy array to a Python list, for example:
[[ 0.] [ 1.] [ 2.] [ 3.] [ 4.]] --> ['0', '1', '2', '3', '4']
How do I convert a NumPy array to a Python list, for example:
[[ 0.] [ 1.] [ 2.] [ 3.] [ 4.]] --> ['0', '1', '2', '3', '4']
You can use numpy's .flatten()
method followed by a list
and map
function.
>>> arr = np.array([[0.],[1.],[2.],[3.],[4.]])
>>> arr = arr.flatten()
>>> arr
array([0., 1., 2., 3., 4.])
>>> arr = list(map(lambda x:f"{x:.0f}", arr))
>>> arr
['0', '1', '2', '3', '4']
First try to understand what the array is:
In [73]: arr = np.array([[ 0.], [ 1.], [ 2.], [ 3.], [ 4.]])
In [74]: arr
Out[74]:
array([[0.],
[1.],
[2.],
[3.],
[4.]])
In [75]: arr.shape, arr.dtype
Out[75]: ((5, 1), dtype('float64'))
There is a good, fast method to convert an array to list - that is close to the original in use of [] and type - floats.
In [76]: arr.tolist()
Out[76]: [[0.0], [1.0], [2.0], [3.0], [4.0]]
If you don't want those inner [], dimension, lets ravel/flatten array. That easier done with the array than the nested list:
In [77]: arr.ravel()
Out[77]: array([0., 1., 2., 3., 4.])
We could also convert the floats to strings:
In [78]: arr.ravel().astype(str)
Out[78]: array(['0.0', '1.0', '2.0', '3.0', '4.0'], dtype='<U32')
In [79]: arr.ravel().astype(str).tolist()
Out[79]: ['0.0', '1.0', '2.0', '3.0', '4.0']
But you want integers - so lets do that conversion first:
In [80]: arr.ravel().astype(int).astype(str).tolist()
Out[80]: ['0', '1', '2', '3', '4']
The other answer show how to do these conversion with lists.
Here's the code:
import numpy as np
arr = np.array([[1], [2], [3]])
print(f'NumPy Array: {arr}')
list1 = arr.tolist()
l = [i for sublist in list1 for i in sublist]
print(f'List: {l}')
You can use a simple for loop
:
import numpy as np
a = [[0.],[1.],[2.],[3.],[4.]]
b = np.asarray(a)
lst=[]
for i in b:
lst.append(str(int(i[0])))
lst
>>>['0', '1', '2', '3', '4']