如何在python中将列表另存为numpy数组?


Answers:


162

如果您在这里看,它可能会告诉您您需要了解的内容。

http://www.scipy.org/Tentative_NumPy_Tutorial#head-d3f8e5fe9b903f3c3b2a5c0dfceb60d71602cf93

基本上,您可以根据序列创建数组。

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

或来自序列序列。

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

21
将numpy导入为np; 并添加np。在array(np.array([]);之前;对于可能会感到困惑的人
Abhi

3
我会将该语法稍有不同。怎么样import numpy as np,然后a = np.array ( [[2,3,4],[3,4,5]] )
SDsolar



16

您想将其另存为文件吗?

import numpy as np

myList = [1, 2, 3]

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

...然后阅读:

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


4

我想,您是说将列表转换为numpy数组?然后,

import numpy as np

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

以reshape给定的形状为您提供a作为列表b的数组。


0

这是一个更完整的示例:

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)

希望这可以帮助!!


0
import numpy as np 

... ## other code

一些列表理解

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

使用numpy库中指定的数组方法将列表转换为numpy数组。

t=np.array(t)

这可能会有所帮助:https : //numpy.org/devdocs/user/basics.creation.html


0

也许:

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

输出:

<class 'numpy.ndarray'>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.