我有 2 個相同長度的 numpy 陣列,讓我們將它們稱為 A 和 B 以及 2 個名為 C 和 D 的標量值。我想將這些值存盤到單個 txt 檔案中。我想到了以下結構:

它不必具有這種格式,我只是認為它方便且清晰。我知道如何將 numpy 陣列寫入 txt 檔案并再次讀取它們,但我很難將 txt 檔案寫入陣列和標量值的組合,以及如何將它們從 txt 再次讀取到 numpy。
A = np.array([1, 2, 3, 4, 5])
B = np.array([5, 4, 3, 2, 1])
C = [6]
D = [7]
np.savetxt('file.txt', (A, B))
A_B_load = np.loadtxt('file.txt')
A_load = A_B_load[0,:]
B_load= A_B_load[1,:]
這并沒有給我我提出的相同的列結構,而是將陣列存盤在行中,但這并不重要。
我發現了一個有點不方便的解決方案,因為我必須用 0 填充標量值才能使它們變得像陣列 A 和 B 一樣具有相同的長度,必須有一個更智能的解決方案。
A = np.array([1, 2, 3, 4, 5])
B = np.array([5, 4, 3, 2, 1])
C = [6]
D = [7]
fill = np.zeros(len(A)-1)
C = np.concatenate((C,fill))
D = np.concatenate((D, fill))
np.savetxt('file.txt', (A,B,C,D))
A_B_load = np.loadtxt('file.txt')
A_load = A_B_load[0,:]
B_load = A_B_load[1,:]
C_load = A_B_load[2,0]
D_load = A_B_load[3,0]
uj5u.com熱心網友回復:
一個更聰明的解決方案可能是使用 pandas 而不是 numpy (如果這是您的選擇):
df = pd.concat([pd.DataFrame(arr) for arr in [A,B,C,D]], axis=1)
df.to_csv("test.txt", na_rep="", sep=" ", header=False, index=False)
a = pd.read_csv("test.txt", sep=" ", header=None).values
第一行通過連接所有陣列來創建一個資料框。Pandas 的默認行為是用 NaN 替換缺失值。第二行寫入輸出檔案,用空字串替換 NaN(因為您似乎關心檔案大小)。最后一行給你一個 numpy 陣列:
In [45]: a
Out[45]:
array([[ 1., 5., 6., 7.],
[ 2., 4., nan, nan],
[ 3., 3., nan, nan],
[ 4., 2., nan, nan],
[ 5., 1., nan, nan]])
uj5u.com熱心網友回復:
In [123]: A = np.array([1, 2, 3, 4, 5])
...: B = np.array([5, 4, 3, 2, 1])
...: C = [6]
...: D = [7]
savetxt旨在以一致的 csv 格式撰寫二維陣列 - 一個整齊的表格,每行中的列數相同。
In [124]: arr = np.stack((A,B), axis=1)
In [125]: arr
Out[125]:
array([[1, 5],
[2, 4],
[3, 3],
[4, 2],
[5, 1]])
這是一種可能的寫入格式:
In [126]: np.savetxt('foo.txt', arr, fmt='%d', header=f'{C} {D}', delimiter=',')
...:
In [127]: cat foo.txt
# [6] [7]
1,5
2,4
3,3
4,2
5,1
我將標量放在標題行中,因為它們與陣列不匹配。
loadtxt可以重新創建該arr陣列:
In [129]: data = np.loadtxt('foo.txt', dtype=int, skiprows=1, delimiter=',')
In [130]: data
Out[130]:
array([[1, 5],
[2, 4],
[3, 3],
[4, 2],
[5, 1]])
標題行可以閱讀:
In [138]: with open('foo.txt') as f:
...: header = f.readline().strip()
...: line = header[1:]
...:
In [139]: line
Out[139]: ' [6] [7]'
我應該把它保存為更容易決議的東西,比如'# 6,7'
您接受的答案會nan在 csv 中創建一個包含值和空白的資料框
In [143]: import pandas as pd
In [144]: df = pd.concat([pd.DataFrame(arr) for arr in [A,B,C,D]], axis=1)
...: df.to_csv("test.txt", na_rep="", sep=" ", header=False, index=False)
In [145]: df
Out[145]:
0 0 0 0
0 1 5 6.0 7.0
1 2 4 NaN NaN
2 3 3 NaN NaN
3 4 2 NaN NaN
4 5 1 NaN NaN
In [146]: cat test.txt
1 5 6.0 7.0
2 4
3 3
4 2
5 1
請注意,這np.nan是一個浮點數,因此某些列是浮點數。 loadtxt無法處理那些“空白”列;np.genfromtxt更好,但它需要一個分隔符,來標記它們。
撰寫和讀取全長陣列很容易。但是混合型別會變得混亂。
這是一種更易于書寫和閱讀的格式:
In [149]: arr = np.zeros((5,4),int)
...: for i,var in enumerate([A,B,C,D]):
...: arr[:,i] = var
...:
In [150]: arr
Out[150]:
array([[1, 5, 6, 7],
[2, 4, 6, 7],
[3, 3, 6, 7],
[4, 2, 6, 7],
[5, 1, 6, 7]])
In [151]: np.savetxt('foo.txt', arr, fmt='%d', delimiter=',')
In [152]: cat foo.txt
1,5,6,7
2,4,6,7
3,3,6,7
4,2,6,7
5,1,6,7
In [153]: np.loadtxt('foo.txt', delimiter=',', dtype=int)
Out[153]:
array([[1, 5, 6, 7],
[2, 4, 6, 7],
[3, 3, 6, 7],
[4, 2, 6, 7],
[5, 1, 6, 7]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/468194.html
下一篇:從二維陣列中洗掉值
