I have three numpy arrays of shape (250L,)
called c
, I
and error
. I want to be able to save the three arrays to a text file so that each array is one column in the file. So far I have tried the following:
DataArray = np.concatenate((c,I,Error),axis=1)
np.savetxt('VaryingC.txt',DataArray)
This returns an error since the initial arrays are 1D:
IndexError: axis 1 out of bounds [0, 1)
How can I combine the three arrays to make a shape (250,3)
array?
concatenate
连接现有的轴, stack
插入新的轴:
DataArray = np.stack((c,I,Error),axis=1)
It seems you are looking for:
DataArray = np.column_stack((c,I,Error))
Timing:
In [201]: a1 = np.random.randint(10**6, size=10**6)
In [202]: a2 = np.random.randint(10**6, size=10**6)
In [203]: a3 = np.random.randint(10**6, size=10**6)
In [204]: %timeit np.column_stack((a1,a2,a3))
100 loops, best of 3: 14.1 ms per loop
In [205]: %timeit np.stack((a1,a2,a3),axis=1)
100 loops, best of 3: 14.2 ms per loop
In [206]: %timeit np.transpose([a1,a2,a3])
100 loops, best of 3: 10.7 ms per loop
In your case you could just create a new array and then transpose it:
np.transpose([c, I, Error])
np.transpose
automatically creates a new array, so you don't need to create one yourself.
For example:
>>> import numpy as np
>>> a = np.array([1, 1, 1, 1, 1])
>>> b = np.array([2, 2, 2, 2, 2])
>>> c = np.array([3, 3, 3, 3, 3])
>>> DataArray = np.transpose([a, b, c])
>>> DataArray
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
>>> DataArray.shape
(5, 3)
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.