Convert Numpy Array to Python List

Convert NumPy array to Python list

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.)

Converting numpy array to a list

If you have a numpy.ndarray, then try this:

>>> import numpy
>>> lst = [6.72599983, -7.15100002, 4.68499994]
>>> numpy.asarray(lst)
array([ 6.72599983, -7.15100002, 4.68499994])
>>> list(numpy.asarray(lst))
[6.7259998300000001, -7.1510000199999997, 4.68499994]

If you have wrongly casted the numpy.array into a string, then you need to use that cleaning trick with ast to get it into a list.

>>> import ast, numpy
>>> s = str(numpy.asarray(lst))
>>> s
'[ 6.72599983 -7.15100002 4.68499994]'
>>> list(ast.literal_eval(",".join(s.split()).replace("[,", "[")))
[6.72599983, -7.15100002, 4.68499994]

numpy.array.tolist() converts numpy.datetime64 to int

Explicitly casting the numpy.ndarray as a native Python list will preserve the contents as numpy.datetime64 objects:

>>> list(my_array)
[numpy.datetime64('2017-06-28T22:47:51.213500000'),
numpy.datetime64('2017-06-28T22:48:37.570900000'),
numpy.datetime64('2017-06-28T22:49:46.736800000'),
numpy.datetime64('2017-06-28T22:50:41.866800000'),
numpy.datetime64('2017-06-28T22:51:17.024100000'),
numpy.datetime64('2017-06-28T22:51:24.038300000')]

However, if you wanted to go back from an integer timestamp to a numpy.datetime64 object, the number given here by numpy.ndarray.tolist is given in nanosecond format, so you could also use a list comprehension like the following:

>>> [np.datetime64(x, "ns") for x in my_list]
[numpy.datetime64('2017-06-28T22:47:51.213500000'),
numpy.datetime64('2017-06-28T22:48:37.570900000'),
numpy.datetime64('2017-06-28T22:49:46.736800000'),
numpy.datetime64('2017-06-28T22:50:41.866800000'),
numpy.datetime64('2017-06-28T22:51:17.024100000'),
numpy.datetime64('2017-06-28T22:51:24.038300000')]

And if you want the final result as a Python datetime.datetime object instead of a numpy.datetime64 object, you can use a method like this (adjusted as needed for locality):

>>> from datetime import datetime
>>> list(map(datetime.utcfromtimestamp, my_array.astype(np.uint64) / 1e9))
[datetime.datetime(2017, 6, 28, 22, 47, 51, 213500),
datetime.datetime(2017, 6, 28, 22, 48, 37, 570900),
datetime.datetime(2017, 6, 28, 22, 49, 46, 736800),
datetime.datetime(2017, 6, 28, 22, 50, 41, 866800),
datetime.datetime(2017, 6, 28, 22, 51, 17, 24100),
datetime.datetime(2017, 6, 28, 22, 51, 24, 38300)]

Edit: Warren Weckesser's answer provides a more straightforward approach to go from a numpy.datetime64[ns] array to a list of Python datetime.datetime objects than is described here.

Convert a NumPy array to a binary array with the condition of each element existing in a list

Check out https://numpy.org/doc/stable/reference/generated/numpy.isin.html

arr=np.array([[23,43,1],[43,5,0],[5,0,0]])
l = [5,43]
np.isin(arr, l).astype(int)
#array([[0, 1, 0],
# [1, 1, 0],
# [1, 0, 0]])

Convert numpy array to a range

Since it's tagged as numpy, here is a numpy solution (sort of). There is no native numpy function but you could use diff + where + split + list comprehension:

>>> [[ary[0], ary[-1]] if len(ary)>1 else [ary[0]] for ary in np.split(arr, np.where(np.diff(arr) != 1)[0] + 1)]
[[1, 4], [6, 9], [14, 18], [25, 36], [38], [45]]

If the array is large, it's more efficient to use a loop rather than np.split, so you could use the function below which produces the same outcome as above:

def array_to_range(arr):
idx = np.r_[0, np.where(np.diff(arr) != 1)[0]+1, len(arr)]
out = []
for i,j in zip(idx, idx[1:]):
ary = arr[i:j]
if len(ary) > 1:
out.append([ary[0], ary[-1]])
else:
out.append([ary[0]])
return out


Related Topics



Leave a reply



Submit