0

How do I convert a NumPy array to a Python list, for example:

[[ 0.] [ 1.] [ 2.] [ 3.] [ 4.]] --> ['0', '1', '2', '3', '4']
Jérôme Richard
  • 41,678
  • 6
  • 29
  • 59
SNM
  • 15
  • 3

4 Answers4

1

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']
Gusti Adli
  • 1,225
  • 4
  • 13
1

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.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

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}')
Ishwar
  • 338
  • 2
  • 11
  • My array like this [[ 0.] [ 1.] [ 2.] [ 3.] [ 4.]] not [1, 2, 3] – SNM Apr 30 '21 at 00:47
  • Modified the code to work as you requested. arr.tolist() converts numpy array to a 2D list. The list comprehension flattens 2D list to a single dimensional list. – Ishwar Apr 30 '21 at 00:59
0

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']
zoldxk
  • 2,632
  • 1
  • 7
  • 29