【发布时间】: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