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']
ravel over flatten when you need a read-only viewFirst 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.
you don't really need more than the following and the key part is numpy.reshape to remove your nested arrays. the rest is just casting to get rid of decimals and convert to strings, respectively:
# [[ 0.] [ 1.] [ 2.] [ 3.] [ 4.]] --> ['0', '1', '2', '3', '4']
import numpy as np
inputArray = np.array([[ 0.],[ 1.],[ 2.],[ 3.],[ 4.]])
inputArray = inputArray.reshape(-1).astype(np.int32).astype(str).tolist()
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}')
my_array.tolist()???