简体   繁体   English

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

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

I have the following code that generates numpy list, writes it, and later reads it back as a numpy list again: 我有以下代码生成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)

The output looks like this: 输出看起来像这样:

['[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]']

How can I remove single quotation mark around each vector so that it become a numpy vector? 如何删除每个向量周围的单引号,使之成为一个numpy向量? In other word, instead of '[0 0 0 1 0]' , it must be [0 0 0 1 0] . 换句话说,它必须是[0 0 0 1 0]而不是'[0 0 0 1 0]' I tried using l = np.asarray(line.strip()) but it seems it has no effect when appending. 我尝试使用l = np.asarray(line.strip())但附加时似乎没有效果。 Note that I do looping while read and write on purpose. 请注意,我在故意读写时会循环播放。

Thank you 谢谢

There are easier ways to re-read the output if you write it out in a better format. 如果以更好的格式写输出,则有更简单的方法可以重新读取输出。 Assuming you have a reason to output it the way you did, and if you don't care about the data structure when it's read back in... 假设您有理由按您的方式输出它,并且如果您不关心读回时的数据结构...

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