【问题标题】:append an numpy ndarray to another one along certain dimensions沿着某些维度将一个 numpy ndarray 附加到另一个
【发布时间】:2021-10-20 17:38:08
【问题描述】:

存在两个numpy.ndarray,例如A的形状为(5,3,2)B的形状为(5,3)

A = np.random.rand(5,3,2)
B=np.random.rand(5,3)  #----- there was typo here

我想将 B 附加到 A 中,并将结果数组 C 与形状 (5,3,3) 我尝试使用 np.contaenate,但它不起作用。

c=np.concatenate((a,b),axis=2) 

【问题讨论】:

  • 错误是什么?您对如何纠正它有任何想法吗? “它不起作用”是不够的!
  • 你可以使用reshape:np.concatenate((np.arange(30).reshape(5, 3, 2), np.arange(15).reshape(5, 3, 1)), axis=2)
  • 即先做 B = B.reshape(5,3,1) 而不是连接

标签: python-3.x numpy scipy numpy-ndarray array-broadcasting


【解决方案1】:
import numpy as np

a = np.random.rand(5,3,2)
b = np.random.rand(5,3)

b = b[..., np.newaxis] # or np.expand_dims(b, axis=2) or b.reshape(b.shape+(1,))
print(b) # (5, 3, 1)
c = np.append(a, b, axis=2)
print(c.shape) # (5, 3, 2)

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 2018-06-05
    • 2016-05-16
    • 2015-02-01
    • 2018-04-12
    • 2023-03-12
    • 2016-02-29
    • 1970-01-01
    相关资源
    最近更新 更多