You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将shape为(5,4)的numpy矩阵扩展为shape为(5,4,n)(n≠1)的矩阵

解决方案

你可以通过沿新增的最后一个维度做重复操作实现,以下是几种常用方案:

  • 方案1:np.repeat(最常用,生成独立可修改的数组)
    直接对新增维度做元素级重复,修改生成后的数组不会影响原数组,也不会出现重复值联动的问题:
import numpy as np

# 原始矩阵
matrix1 = np.array([
    [80, 80, 80, 80],
    [0, 50, 0, 0],
    [0, 0, 50, 0],
    [0, 0, 0, 50],
    [30, 30, 30, 30]
])
n = 6 # 替换为你需要的任意正整数
matrix_n = np.repeat(matrix1[..., np.newaxis], repeats=n, axis=-1)
print(matrix_n.shape) # 输出 (5, 4, 6)
  • 方案2:np.tile(适合数组拼接场景)
    对整个数组按维度倍数拼接,当前最后一维长度为1时,效果和np.repeat完全一致:
n = 4
matrix_n = np.tile(matrix1[..., np.newaxis], reps=(1, 1, n))
print(matrix_n.shape) # 输出 (5, 4, 4)
  • 方案3:np.broadcast_to(内存友好的只读方案)
    不会实际复制数据,仅生成逻辑上符合目标shape的视图,内存占用几乎不随n增大而增加,但修改视图会导致所有重复位置同步变更,仅适合只读场景:
n = 20
matrix_n = np.broadcast_to(matrix1[..., np.newaxis], shape=(matrix1.shape[0], matrix1.shape[1], n))
print(matrix_n.shape) # 输出 (5, 4, 20)

内容的提问来源于stack exchange,提问作者KansaiRobot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:24:02