【问题标题】:Duplicating vector along an arbitrary number of dimensions沿任意维数复制向量
【发布时间】:2020-10-28 15:50:21
【问题描述】:

我想沿着另一个数组的维度重复1D-array,知道这个维度的数量可以改变。

例如:

import numpy as np
to_repeat = np.linspace(0, 100, 10)
base_array = np.random.random((24, 60)) ## this one can have more than two dimensions.

final_array = np.array([[to_repeat for i in range(base_array.shape[0])] for j in range(base_array.shape[1])]).T
print(final_array.shape)
# >>> (10, 24, 60)

如何将其扩展到具有任意维数的数组base_array? 可能使用numpy 向量化函数以避免循环?


编辑(大图):

base_array实际上是(10, 24, 60)的形状(如果我们坚持这个例子),其中沿第一维的坐标是向量to_repeat

我正在寻找沿base_array 的第一个维度的最小值,并创建相应坐标的数组,这里的形状为(24, 60)

【问题讨论】:

  • 你用这个做什么?因为你几乎肯定想要广播 to_repeat 而不是实际制作 final_array
  • 查看我编辑的问题!

标签: python numpy


【解决方案1】:

你不需要final_array,你可以通过以下方式得到你想要的结果:

to_repeat[base_array.argmin(0)]

【讨论】:

  • 这个返回Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: index 18 is out of bounds for axis 0 with size 10
  • 您需要提供可运行的代码,清楚地显示您的输入形状和预期输出。如果base_array.shape = (10, 24, 60) 如您所说,argmin(0) 不应返回 18。
  • 抱歉,我在运行您的答案时打错了字。它确实完美无缺。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 2017-01-02
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 2019-08-15
  • 2012-11-14
相关资源
最近更新 更多