I have created a number of random numpay arrays:
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 ) )
as you can see they are in different length size, now I want to combine them so I can save them later to excel or CSV file for later use.
I have tried all the faloweng scrpets:
#x = np.column_stack( ( x1 , x2 ))
------------
x = np.concatenate((x1, x2[:,None]), axis=1)
but didn't work and that clear because each one has different size x1 (10,1) - x2 (5,1)
I am not sure if there any way to concatenate them without any problems, for example, filling the missing ones with None just to make them equal, or any ideas that can help?
padding it with np.nan
is a valid option.
create an empty target array, and just assign your arrays into it's sub indexes:
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)
Output:
[[ -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]]
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.