![](/img/trans.png)
[英]Python: How to save lists of 2D numpy arrays of different lengths
[英]How to stack 2 numpy arrays with Different Lengths in python
我創建了一些隨機的 numpay 數組:
import numpy as np
x1 = np.random.normal( 0, 1, ( 10, 1 ) )
x2 = np.random.normal( 0, 2, ( 5, 1 ) )
x3 = np.random.normal( 0, 3, ( 7, 1 ) )
x4 = np.random.normal( 0, 4, ( 9, 1 ) )
正如您所看到的,它們的長度大小不同,現在我想將它們組合起來,以便稍后將它們保存到 excel 或 CSV 文件中以備后用。
我已經嘗試了所有的 faloweng screts:
#x = np.column_stack( ( x1 , x2 ))
------------
x = np.concatenate((x1, x2[:,None]), axis=1)
但沒有用,而且很清楚,因為每個都有不同的大小x1 (10,1) - x2 (5,1)
我不確定是否有任何方法可以毫無問題地將它們連接起來,例如,用 None 填充缺失的那些只是為了使它們相等,或者任何可以提供幫助的想法?
用np.nan
填充它是一個有效的選擇。
創建一個空的目標數組,然后將數組分配到它的子索引中:
import numpy as np
x1 = np.random.normal( 0, 1, ( 10, 1 ) )
x2 = np.random.normal( 0, 2, ( 5, 1 ) )
x3 = np.random.normal( 0, 3, ( 7, 1 ) )
x4 = np.random.normal( 0, 4, ( 9, 1 ) )
arrs = [x1,x2,x3,x4]
a = np.empty((max(x.shape[0] for x in arrs), len(arrs)))
a[:] = np.nan
for i, x in enumerate(arrs):
a[0:len(x), i] = x.T
print(a)
輸出:
[[ -1.5521545 -1.82217348 -3.28589422 -1.59646125]
[ 0.54409311 2.53585401 -2.15704799 2.1590175 ]
[ 0.24202617 -1.62680388 0.58507172 4.24671516]
[ 1.21341942 -2.09405961 1.94415747 -1.21781288]
[ -0.53110862 1.47037056 2.37113853 -10.01200676]
[ 0.50884432 nan -2.56881482 -3.52164926]
[ -0.37551321 nan 0.67952001 -0.5523079 ]
[ 0.5943706 nan nan -6.25704491]
[ -0.37893229 nan nan -6.28029336]
[ -0.34746679 nan nan nan]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.