How to save a list as numpy array in python?

PythonListNumpy

Python Problem Overview


Is possible to construct a NumPy array from a python list?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

you mean something like this ?

from numpy  import array
a = array( your_list )

Solution 3 - Python

Yes it is:

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

Solution 4 - Python

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

Solution 5 - Python

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

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

Solution 6 - Python

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.

Solution 7 - Python

Here is a more complete example:

import csv
import numpy as np

with open('filename','rb') as csvfile:
     cdl = list( csv.reader(csvfile,delimiter='\t'))
     print "Number of records = " + str(len(cdl))

#then later

npcdl = np.array(cdl)

Hope this helps!!

Solution 8 - Python

import numpy as np 

... ## other code

some list comprehension

t=[nodel[ nodenext[i][j] ] for j in idx]
            #for each link, find the node lables 
            #t is the list of node labels 

Convert the list to a numpy array using the array method specified in the numpy library.

t=np.array(t)

This may be helpful: https://numpy.org/devdocs/user/basics.creation.html

Solution 9 - Python

maybe:

import numpy as np
a=[[1,1],[2,2]]
b=np.asarray(a)
print(type(b))

output:

<class 'numpy.ndarray'>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHosseinView Question on Stackoverflow
Solution 1 - PythonBryce SiedschlawView Answer on Stackoverflow
Solution 2 - PythonCédric JulienView Answer on Stackoverflow
Solution 3 - PythonFelix KlingView Answer on Stackoverflow
Solution 4 - PythoneumiroView Answer on Stackoverflow
Solution 5 - PythonBilalView Answer on Stackoverflow
Solution 6 - PythonHadamardView Answer on Stackoverflow
Solution 7 - PythonSDsolarView Answer on Stackoverflow
Solution 8 - PythonThermoRestartView Answer on Stackoverflow
Solution 9 - PythonRaazescytheView Answer on Stackoverflow