Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a list as numpy array in python?

Tags:

python

list

numpy

People also ask

How do I save a list as a NumPy array?

import numpy as np # b is some list, then ... a = np. array(b). reshape(lengthDim0, lengthDim1); gives you a as an array of list b in the shape given in reshape.

Can we convert list to NumPy array?

You can convert a list to a NumPy array by passing a list to numpy. array() . The data type dtype of generated numpy. ndarray is automatically determined from the original list but can also be specified with the dtype parameter.

How do I turn a list into a array in Python?

To convert a list to array in Python, use the np. array() method. The np. array() is a numpy library function that takes a list as an argument and returns an array containing all the list elements.


First of all, I'd recommend you to go through NumPy's Quickstart tutorial, which will probably help with these basic questions.

You can directly create an array from a list as:

import numpy as np
a = np.array( [2,3,4] )

Or from a from a nested list in the same way:

import numpy as np
a = np.array( [[2,3,4], [3,4,5]] )

you mean something like this ?

from numpy  import array
a = array( your_list )

Yes it is:

a = numpy.array([1,2,3])

You want to save it as a file?

import numpy as np

myList = [1, 2, 3]

np.array(myList).dump(open('array.npy', 'wb'))

... and then read:

myArray = np.load(open('array.npy', 'rb'))

You can use numpy.asarray, for example to convert a list into an array:

>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])

I suppose, you mean converting a list into a numpy array? Then,

import numpy as np

# b is some list, then ...    
a = np.array(b).reshape(lengthDim0, lengthDim1);

gives you a as an array of list b in the shape given in reshape.