簡體   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