python - 使用由整数 [0,...,L-1] 索引的额外列将 numpy 数组 (N,M,L) 转换为 (N*L,M+1)

标签 python arrays numpy

让我们考虑这个简单的例子:

import numpy as np

a=np.arange(90)
a=a.reshape(6,3,5)

我想得到一个数组 b形状 (6*5,3+1=4) 与
b[0:6,0]=a[:,0,0]
b[0:6,1]=a[:,1,0]
b[0:6,2]=a[:,2,0]
b[0:6,3]=0

b[6:12,0]=a[:,0,1]
b[6:12,1]=a[:,1,1]
b[6:12,2]=a[:,2,1]
b[6:12,3]=1
...
我可以用 for 循环来做到这一点,但我相信还有更优雅的解决方案。

最佳答案

我首先对数组的轴重新排序,然后分配更大的结果数组,然后使用两个(广播)分配来设置新值:

import numpy as np

a = np.arange(6*3*5).reshape(6, 3, 5)  # shape (N, M, L)

aux = a.transpose(0, 2, 1)  # shape (N, L, M)
res = np.empty_like(a, shape=aux.shape[:-1] + (aux.shape[-1] + 1,))
res[..., :-1] = aux  # (N, L, M)-shaped slice
res[..., -1] = np.arange(aux.shape[1])  # (N, L)-shaped slice

# two different interpretations:
#res = res.reshape(-1, res.shape[-1])  # shape (N*L, M + 1)
res = res.transpose(0, 1, 2).reshape(-1, res.shape[-1])  # shape (N*L, M + 1)
在您的问题的两种解释中,后者(未注释版本)复制了您在评论中发布的“脏版本”。如果这确实是您所需要的,我们可以以放置 L 的方式进行原始转置。 -尺寸轴第一:
import numpy as np

a = np.arange(6*3*5).reshape(6, 3, 5)  # shape (N, M, L)

aux = a.transpose(2, 0, 1)  # shape (L, N, M)
res = np.empty_like(a, shape=aux.shape[:-1] + (aux.shape[-1] + 1,))
res[..., :-1] = aux  # (L, N, M)-shaped slice
res[..., -1] = np.arange(aux.shape[0])[:, None]  # (L, N)-shaped slice

res = res.reshape(-1, res.shape[-1])  # shape (N*L, M + 1)

关于python - 使用由整数 [0,...,L-1] 索引的额外列将 numpy 数组 (N,M,L) 转换为 (N*L,M+1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68347548/

相关文章:

python - 移位 "1<<i"在 Python 中如何工作?

python - 没有名为 'scipy.io.matlab' 的模块

python - 在Python中读取文件后尝试创建x和y值的数组

python - 在没有 np.concatenate 或 np.append 的情况下将 3D numpy 数组转换为 2D

python - Numpy NdArray 记忆化

python - 根据字符串长度追加

python - JSON 数组作为 Python 请求中的单个参数值

c - 搜索结构数组

java - 将可扩展数组索引(Ix 和系列)移植到 Java

python - 奇异矩阵 - python