【问题标题】:Combining and reshape-ing ndarray so that original values of each component are on the first axis合并和重塑ndarray,使每个组件的原始值在第一个轴上
【发布时间】:2019-10-09 06:04:21
【问题描述】:

对于numpy stackslinear algebra,您希望使用第一轴上的堆栈来格式化数据。

例如,要使用determinant,参数需要是一个数组,其中最后两个轴是对称的,例如(x,M,M)

如何将四个单独的扁平数组(对应于 2x2 矩阵的系数)重新格式化为这样的格式?

我一直在修补 https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html#numpy.concatenatehttps://docs.scipy.org/doc/numpy/reference/generated/numpy.block.html#numpy.blockhttps://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html

但到目前为止还没有把它变成我认为我需要的格式。

例如,我非常接近

a = np.array([1, 2, 3, 4, 5])
b = np.array([10, 20, 30, 40, 50])
c = np.array([15, 16, 17, 18, 19])
d = np.array([100, 200, 300, 400, 500])
result = np.dstack((a, b, c, d))
result = np.reshape(result, (1, 5, 2, 2))
print("RESULT SHAPE", result.shape)
print("RESULT VALUE", result[:, :, 0, 0])
print("RESULT I REALLY WANT", result[:, 0, 0])

不确定如何删除最后一个轴。

【问题讨论】:

  • 等等,我现在感觉很笨。我想我可以这样做:new_result = np.reshape(result, (-1, 2, 2)) 有没有比顺序执行此操作更简单的方法?

标签: python numpy multidimensional-array


【解决方案1】:
In [250]: a = np.array([1, 2, 3, 4, 5]) 
     ...: b = np.array([10, 20, 30, 40, 50]) 
     ...: c = np.array([15, 16, 17, 18, 19]) 
     ...: d = np.array([100, 200, 300, 400, 500])      

np.stackconcatenate 的一个版本,它在新轴上连接数组 - 我们可以选择:

In [251]: np.stack((a,b,c,d)).shape                                             
Out[251]: (4, 5)
In [252]: np.stack((a,b,c,d),1).shape                                           
Out[252]: (5, 4)

然后我们可以将最后一个轴重塑为 (2,2):

In [253]: np.stack((a,b,c,d),1).reshape(5,2,2)                                  
Out[253]: 
array([[[  1,  10],
        [ 15, 100]],

       [[  2,  20],
        [ 16, 200]],

       [[  3,  30],
        [ 17, 300]],

       [[  4,  40],
        [ 18, 400]],

       [[  5,  50],
        [ 19, 500]]])

第一个堆栈与np.array相同:

In [254]: np.array((a,b,c,d)).shape                                             
Out[254]: (4, 5)
In [255]: np.array((a,b,c,d)).reshape(2,2,5)                                    
Out[255]: 
array([[[  1,   2,   3,   4,   5],
        [ 10,  20,  30,  40,  50]],

       [[ 15,  16,  17,  18,  19],
        [100, 200, 300, 400, 500]]])

现在使用 transpose 将 5 个批次维度移到开头:

In [256]: np.array((a,b,c,d)).reshape(2,2,5).transpose(2,0,1)  

因此,有多种方法可以连接数组和调整维度。我不认为任何人天生就更简单。 reshapetranspose 很便宜,所以请随意使用。

【讨论】:

  • 感谢您提供详细的文章和您找到的解决方案。我意识到np.stack((a,b,c,d),1) 在功能上等同于我在重新塑造后上面的np.dstack((a, b, c, d))
猜你喜欢
  • 2021-06-01
  • 2018-12-24
  • 2022-01-01
  • 2016-07-10
  • 1970-01-01
  • 2018-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多