ChatGPT解决这个技术问题 Extra ChatGPT

Converting NumPy array into Python List structure?

How do I convert a NumPy array to a Python List (for example [[1,2,3],[4,5,6]] ), and do it reasonably fast?


P
Peter Hansen

Use tolist():

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)


If your list is float32 tolist will convert it to floatss - that's not desired probably. Using list(myarray) doesn't suffer from this - why should we prefer tolist ?
@Mr_and_Mrs_D are you suggesting that, despite having floats in your array, you'd like to have the resulting list be integers? That's sort of a whole different question... and of course you'd have to specify that despite being float32 values, they're all going to be integral. Anyway, if you had that situation, I guess doing myarray.astype(np.int32).tolist() would be an option, and explicit about what you're trying to accomplish. (And lastly, list(array_of_type_float32) doesn't give integers here when I tried it... so I don't know what you're asking.)
I never mentioned integers - try float32_array = np.array([0.51764709], np.float32); print(float32_array.tolist()); print(list(float32_array))
Okay, so the one converts to [float] and the other uses the numpy scalar float32 type still, as [np.float32]. Fine. Good to know, but I guess whether it's desirable or not depends on each specific case. For what it's worth, I suspect that generally when someone (like the OP) asks for conversion to a list, they implicitly mean a list of regular Python data types, in this case either floats or integers, and not a list of numpy scalar types. Thanks for pointing this out: I've edited the answer to include a note about that.
Along those lines: np.array([[0, 'one'], ['two', 3]]).tolist() -> [['0', 'one'], ['two', '3']]
B
BUFU

The numpy .tolist method produces nested lists if the numpy array shape is 2D.

if flat lists are desired, the method below works.

import numpy as np
from itertools import chain

a = [1,2,3,4,5,6,7,8,9]
print type(a), len(a), a
npa = np.asarray(a)
print type(npa), npa.shape, "\n", npa
npa = npa.reshape((3, 3))
print type(npa), npa.shape, "\n", npa
a = list(chain.from_iterable(npa))
print type(a), len(a), a`

to get a flat list, there is also a.flatten().tolist() (or list(a.flatten()) cf discussion above)
@ClementWalter Thanks! That comment is worth much more than the answer itself. Do you happen to know why .tolist() creates a nested list? Why do we have to go through so many steps to get a simple list? What's the rationale?
@deps_stats this is because np.array(arr.tolist()) == arr; in other words .tolist is sort of a serialization of arr
H
Harshal SG

c = np.array([[1,2,3],[4,5,6]])

list(c.flatten())

S
Shivid

tolist() works fine even if encountered a nested array, say a pandas DataFrame;

my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]

print(type(my_list),type(my_dt),type(new_list))

r
rahul-ahuja

Another option

c.ravel()
# or
c.ravel().tolist()

also works.