首页 > 解决方案 > 如何通过将最后一个元素复制 3 次将 (z,x,y,1) 形状的 numpy 数组转换为 (z,x,y,3) 形状的 numpy 数组?

问题描述

我想通过复制最后一个元素将 -(z,x,y,1)形的 numpy 数组变成- 形的 numpy 数组?(z,x,y,3)

例如给出

import numpy as np
# The shape is (1,2,2,1) (that is z=1, x=2, y=2)
a = np.array([[[[1], [2]],[[3], [4]]]])
print(a.shape) 

# I want to make it (1,2,2,3) by duplicating the last element 3 times as follow
a = np.array([[[[1,1,1], [2,2,2]],[[3,3,3], [4,4,4]]]]) 
print(a.shape)

所以给定一个 numpy 数组ashape ,如何通过复制最后一个元素(z,x,y,1)使其成为numpy 数组?(z,x,y,3)

标签: pythonarraysnumpy

解决方案


尝试这个:

def repeat_last(a, n=3):
    a.repeat(n, axis=2).reshape(*a.shape[:-1], n)

推荐阅读