【问题标题】:numpy sub-gridding an cartesian productnumpy子网格化笛卡尔积
【发布时间】:2023-03-14 19:25:01
【问题描述】:

所以我有两个(或更多)向量 a 和 b 的笛卡尔积 c。我想从 c 中得到 a[::i] 和 b[::j] 的笛卡尔积。

这意味着新的笛卡尔积将跳过每个第 i 个 a 项和每个第 j 个 b 项。

例如

veclens = (3,6)

# <code that generates cross product c here> (I have that). 
# result:
c = array([
[0,0],
[0,1],
[0,2],
[0,3],
[0,4],
[0,5],
[1,0],
[1,1],
[1,2],
[1,3],
[1,4],
[1,5],
[2,0],
[2,1],
[2,2],
[2,3],
[2,4],
[2,5]])

print c.shape 
(18, 2)

samples = (2,2) # so we want every 2nd item a, and every 2nd in b

# this is the function I would like:
d = get_subarray(c, samples, veclens)

# and now d is something like
array([
[0,0],
[0,2],
[0,4],
[2,0],
[2,2],
[2,4]])

知道如何在不从头计算数组 c 的情况下编写 get_subarray(这很昂贵,因为它实际上是在 a 和 b 的叉积上计算的函数)。肯定有一些索引技巧吗?

我正在寻找类似以下的东西,但更通用、更优雅和更快。

def get_subarray(c, samples, veclens):
    indexes = []
    for i in range(0, veclens[0], samples[0]):
        for j in range(0, veclens[1], samples[1]):
            indexes.append(i * veclens[1] + j)
    return c[indexes]

【问题讨论】:

    标签: python arrays indexing numpy


    【解决方案1】:

    这是使用 ix_ 的一般解决方案:

    def get_subarray(c, samples, veclens):
        n = len(veclens)
        d = c.reshape(veclens+[n])
        i = numpy.ix_(*[range(0, l, s) for l,s in zip(veclens,samples)]
        return d[i].reshape((-1,n)
    

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 2012-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2013-12-25
      相关资源
      最近更新 更多