简体   繁体   中英

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:

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? In other word, instead of '[0 0 0 1 0]' , it must be [0 0 0 1 0] . I tried using l = np.asarray(line.strip()) but it seems it has no effect when appending. 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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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