繁体   English   中英

从文件中读取向量的numpy列表会导致向量更改为字符串

[英]Reading numpy list of vectors from file causes a change of vectors to be string

我有以下代码生成numpy列表,将其写入,然后再次将其读回为numpy列表:

filepath = 'vectors.txt'
rows = 10
dim = 5

V = np.random.choice(np.array([0, 1], dtype=np.uint8), size=(rows, dim))
M = np.unique(V.view(V.dtype.descr * dim))
Matrix = M.view(V.dtype).reshape(-1, dim)

with open(filepath, 'w') as f:
    for i in Matrix:
        f.write("{}\n".format(i))
f.close()


with open(filepath, "r") as f:
    contents = []
    for line in f:
        l = np.asarray(line.strip())
        contents.append(l)
contents = np.asarray(contents)
print(contents)

输出看起来像这样:

['[0 0 0 1 0]' '[0 0 1 0 1]' '[0 0 1 1 1]' '[0 1 0 1 1]' '[0 1 1 0 0]'
 '[0 1 1 0 1]' '[0 1 1 1 0]' '[1 1 1 0 0]' '[1 1 1 0 1]']

如何删除每个向量周围的单引号,使之成为一个numpy向量? 换句话说,它必须是[0 0 0 1 0]而不是'[0 0 0 1 0]' 我尝试使用l = np.asarray(line.strip())但附加时似乎没有效果。 请注意,我在故意读写时会循环播放。

谢谢

如果以更好的格式写输出,则有更简单的方法可以重新读取输出。 假设您有理由按您的方式输出它,并且如果您不关心读回时的数据结构...

with open(filepath, "r") as f:
    contents = []
    for line in f:
        l = np.fromstring(line[1:-1], sep=' ', dtype=int)
        contents.append(l)

>>> contents = np.asarray(contents)
>>> print(contents)
array([[0, 0, 0, 0, 1],
       [0, 1, 0, 0, 0],
       [0, 1, 1, 0, 1],
       [1, 0, 0, 0, 1],
       [1, 0, 1, 0, 1],
       [1, 0, 1, 1, 0],
       [1, 0, 1, 1, 1],
       [1, 1, 0, 1, 1]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM