[英]Copy 2D array to a 3D one - Python / NumPy
I programmed a little bit when I was younger but I was never really good. 我年轻时编程了一点,但我从来都不是很好。 I find Python perfect for what I want to do.
我发现Python非常适合我想做的事情。
I have an Excel file which contains data (64 columns, 18496 lines) that I read using the numpy genfromtxt function. 我有一个Excel文件,其中包含我使用numpy genfromtxt函数读取的数据(64列,18496行)。 I want to put everything in a 3D matrix named H. I use three loops to do so but I know that this is not the most efficient.
我想把所有东西放在一个名为H的3D矩阵中。我使用三个循环来做到这一点,但我知道这不是最有效的。
data = np.genfromtxt(filename, delimiter = ";",skiprows = 11)
H = np.zeros((N,N,Nt))
for k in np.arange(N):
for l in np.arange(N):
for m in np.arange(Nt):
H[k,l,m] = data[m+Nt*k,l]
Is there a cleaver (faster computing wise) to do so. 是否有切割器(更快的计算方式)这样做。 I though about using numpy shape but I'm not able to do it.
我虽然使用numpy形状,但我无法做到。
Thanks 谢谢
You could reshape with np.reshape
& then re-arrange dimensions with np.transpose
, like so - 你可以重塑与
np.reshape
&然后重新安排与尺寸np.transpose
,像这样-
H = data.reshape(N,Nt,N).transpose(0,2,1)
Instead of np.transpose
, one can also use np.swapaxes
as basically we are swapping axes 1,2
there, like so - 而不是
np.transpose
,也可以使用np.swapaxes
因为基本上我们在那里交换axes 1,2
,就像这样 -
H = data.reshape(N,Nt,N).swapaxes(1,2)
Sample run - 样品运行 -
In [300]: N = 2
...: Nt = 3
...: data = np.random.randint(0,9,(N*Nt,N))
...:
In [301]: data
Out[301]:
array([[3, 6],
[7, 4],
[8, 1],
[8, 7],
[4, 8],
[2, 3]])
In [302]: H = np.zeros((N,N,Nt),dtype=data.dtype)
...: for k in np.arange(N):
...: for l in np.arange(N):
...: for m in np.arange(Nt):
...: H[k,l,m] = data[m+Nt*k,l]
...:
In [303]: H
Out[303]:
array([[[3, 7, 8],
[6, 4, 1]],
[[8, 4, 2],
[7, 8, 3]]])
In [304]: data.reshape(N,Nt,N).transpose(0,2,1)
Out[304]:
array([[[3, 7, 8],
[6, 4, 1]],
[[8, 4, 2],
[7, 8, 3]]])
Runtime test - 运行时测试 -
In [8]: # Input
...: N = 10
...: Nt = 10*50
...: data = np.random.randint(0,9,(N*Nt,N))
...:
...: def original_app(data):
...: H = np.zeros((N,N,Nt),dtype=data.dtype)
...: for k in np.arange(N):
...: for l in np.arange(N):
...: for m in np.arange(Nt):
...: H[k,l,m] = data[m+Nt*k,l]
...: return H
...:
In [9]: np.allclose(original_app(data),data.reshape(N,Nt,N).transpose(0,2,1))
Out[9]: True
In [10]: %timeit original_app(data)
10 loops, best of 3: 56.1 ms per loop
In [11]: %timeit data.reshape(N,Nt,N).transpose(0,2,1)
1000000 loops, best of 3: 1.25 µs per loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.