我正在将文件中的数据(数字)读入列表,如下所示:
weight_file = open(model_name, 'r').readlines()
weights = weight_file[6:]
似乎我无法将它们直接读入numpy.array
,因为该文件的第一行包含单词。
现在,在weights
我有一个列表如下:[['1 2 3'] ['4 5 6']]
现在我想将其转换为numpy.array
。我试过这个:
weights_np = np.array([])
for weight in weights:
weights_np = np.append(weights_np, weight.split())
这样做是创建一个向量:[1, 2, 3, 4, 5, 6]
,但我需要将它表示为某种矩阵 - 就像列表一样。我怎么能这样做?
由于
答案 0 :(得分:2)
如果weights_np
是这样的话:
In [23]: weights_np = np.array([1, 2, 3, 4, 5, 6])
然后您可以使用reshape
将其设为2维,包含3列:
In [24]: weights_np = weights_np.reshape((-1, 3))
In [25]: weights_np
Out[25]:
array([[1, 2, 3],
[4, 5, 6]])
但更令人满意的方法是使用np.loadtxt
或np.genfromtxt
正确解析文件。 (这比使用Python循环和调用np.append
要快得多。)请注意,这些函数有一个skiprows
参数,可用于跳过前几行:
weights = np.loadtxt(model_name, skiprows=6)
答案 1 :(得分:2)
要获得"类型的矩阵",只需使用:
numpy.array([[int(val) for val in line.split()] for line in open(model_name)])
要获得简单的向量,请使用:
numpy.array([int(val) for line in open(model_name) for val in line.split()])
答案 2 :(得分:1)
>>> import numpy as np
>>> weights = ['1 2 3', '4 5 6']
>>> weights_np = np.array(map(lambda x: map(int, x.split()), weights))
>>> weights_np
array([[1, 2, 3],
[4, 5, 6]])
答案 3 :(得分:1)
以这种方式尝试:
weights_np = np.empty((0,len(weights[0].split())),int)
for weight in weights:
weights_np = np.append(weights_np, [map(int,weight.split())], axis=0)
演示:
>>> weights = ['1 2 3','4 5 6']
>>> weights_np = np.empty((0,len(weights[0].split())),int)
>>> for weight in weights:
... weights_np = np.append(weights_np, [map(int,weight.split())], axis=0)
...
>>> weights_np
array([[1, 2, 3],
[4, 5, 6]])