【问题标题】:Merge axis in numpy array在numpy数组中合并轴
【发布时间】:2015-11-02 05:16:59
【问题描述】:

我想将 X,Y,Z numpy 数组转换为 (X*Z)*Y numpy 数组。

代码(慢):

 def rearrange(data):
        samples,channels,t_insts=data.shape
        append_data=np.empty([0,channels])
        for sample in range(0,samples):
            for t_inst in range(0,t_insts):
                channel_data=data[sample,:,t_inst]
                append_data=np.vstack((append_data,channel_data))
        return append_data.shape

如果可能的话,我正在寻找更好的矢量化方法

【问题讨论】:

    标签: python arrays numpy vectorization


    【解决方案1】:

    您可以使用np.transposerowscolumns 交换,然后重新整形-

    data.transpose(0,2,1).reshape(-1,data.shape[1])
    

    或者使用np.swapaxes做行列的交换然后reshape -

    data.swapaxes(1,2).reshape(-1,data.shape[1])
    

    【讨论】:

    • 有更通用的方法吗?假设我想将形状数组 (4,5,6,7,8,9) 转换为 (4,5*6*8,7,9)
    • @Gulzar a.transpose(0,1,2,4,3,5) 然后重塑为所需的形状。想法存在 - 将轴按顺序合并,然后重塑。这可能是一个相关的帖子 - stackoverflow.com/a/47978032
    猜你喜欢
    • 2013-04-19
    • 2021-09-05
    • 2015-09-22
    • 1970-01-01
    • 2017-06-03
    • 2020-01-05
    • 2014-03-22
    • 2017-09-19
    • 1970-01-01
    相关资源
    最近更新 更多