【问题标题】:Python: find consecutive values in 3D numpy array without using groupby?Python:在不使用 groupby 的情况下在 3D numpy 数组中查找连续值?
【发布时间】:2017-06-09 00:01:16
【问题描述】:

假设你有以下 3D numpy 数组:

matrices=
numpy.array([[[1, 0, 0], #Level 0
              [1, 1, 1],
              [0, 1, 1]],

             [[0, 1, 0], #Level 1
              [1, 1, 0],
              [0, 0, 0]],

             [[0, 0, 1], #Level 2
              [0, 1, 1],
              [1, 0, 1]]])

并且您想要计算每个单元格获得连续值 1 的次数。假设您要计算每个单元格出现 2 和 3 个连续值 1 的次数。结果应该是这样的:

two_cons=([[0,0,0],
           [1,1,0],
           [0,0,0]])
three_cons=([[0,0,0],
             [0,1,0],
             [0,0,0]])

表示两个单元格至少有 2 个连续值为 1,只有一个单元格有 3 个连续值。

我知道这可以通过使用groupby 来完成,为每个单元格提取“垂直”系列值,并计算您获得n 连续值的次数:

import numpy
two_cons=numpy.zeros((3,3))
for i in range(0,matrices.shape[0]): #Iterate through each "level"
    for j in range(0,matrices.shape[1]):
        vertical=matrices[:,i,j] #Extract the series of 0-1 for each cell of the matrix
        #Determine the occurrence of 2 consecutive values
        cons=numpy.concatenate([numpy.cumsum(c) if c[0] == 1 else c for c in numpy.split(vertical, 1 + numpy.where(numpy.diff(vertical))[0])])
        two_cons[i][j]=numpy.count_nonzero(cons==2)

在这个例子中,你得到了:

two_cons=
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  0.],
       [ 0.,  0.,  0.]])

我的问题:如果我无法访问 vertical,我该怎么做? 在我的真实案例中,3D numpy 数组太大,我无法提取垂直序列许多级别,所以我必须一次循环通过每个级别,并记住之前n级别发生的事情。你有什么建议?

【问题讨论】:

    标签: python arrays numpy probability itertools


    【解决方案1】:

    我还没有检查代码,但是这样的东西应该可以工作......这个想法是沿着第三维扫描矩阵并有 2 个辅助矩阵,一个跟踪实际序列的长度,和一个跟踪迄今为止遇到的最佳序列。

    bests = np.zeros(matrices.shape[:-1])
    counter = np.zeros(matrices.shape[:-1])
    
    for depth in range(matrices.shape[0]):
        this_level = matrices[depth, :, :]
        counter = counter * this_level + this_level
        bests = (np.stack([bests, counter], axis=0)).max(axis=0)
    
    two_con = bests > 1
    three_con = bests > 2
    

    【讨论】:

    • 这一行有问题:for depth in len(matrices.shape[-1]):。你想在这里做什么?
    • 对不起,range() 代替了 len()
    • 现在还有别的东西:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()。我认为它指的是bests = (np.stack(bests, counter)).max(axis=2)
    • 可能是因为我np.stack的语法错误...现在试试吧!
    • 好的,那是因为我扫描的轴有误...(2 而不是 0)我更改了它并检查了它,它现在应该可以工作了
    猜你喜欢
    • 1970-01-01
    • 2015-01-21
    • 2014-09-13
    • 1970-01-01
    • 2021-08-31
    • 2019-02-06
    • 2013-03-16
    • 1970-01-01
    • 2017-06-02
    相关资源
    最近更新 更多