Python中具有周期性边界的数组中的连续值 [英] Consecutive values in array with periodic boundaries in Python
问题描述
我有一些二维数组,其中填充了0
和1
:
I have some 2D-arrays filled with 0
and 1
:
import numpy as np
a = np.random.randint(2, size=(20, 20))
b = np.random.randint(2, size=(20, 20))
c = np.random.randint(2, size=(20, 20))
d = np.random.randint(2, size=(20, 20))
,我想计算具有周期性边界的连续出现次数. 这意味着(为了清楚起见,以1D表示):
and I want to count the consecutive occurrence of the ones with periodic boundaries. That means (in 1D for clearness):
[1 1 0 0 1 1 0 1 1 1]
应该给我5
(后三个元素+前两个元素).
应该在第三个(如果从0开始,则是第二个)轴上比较/计数2D数组,例如首先将数组堆叠在axis=2
中,然后应用与1D相同的算法.但是我不确定这是否是最简单的方法.
should give me 5
(last three elements + first two).
The 2D-arrays should be compared/counted in the third (second if you start with 0) axis, like first stacking the arrays in axis=2
and then applying the same algorithm like for 1D. But I am not sure if this is the most simple way.
推荐答案
这是2D
的ndarrays a
和更高的dim数组的一种方式,旨在提高性能-
Here's one way for ndarrays a
of 2D
and higher dim arrays, meant for performance efficiency -
def count_periodic_boundary(a):
a = a.reshape(-1,a.shape[-1])
m = a==1
c0 = np.flip(m,axis=-1).argmin(axis=-1)+m.argmin(axis=-1)
z = np.zeros(a.shape[:-1]+(1,),dtype=bool)
p = np.hstack((z,m,z))
c = (p[:,:-1]<p[:,1:]).sum(1)
s = np.r_[0,c[:-1].cumsum()]
l = np.diff(np.flatnonzero(np.diff(p.ravel())))[::2]
d = np.maximum(c0,np.maximum.reduceat(l,s))
return np.where(m.all(-1),a.shape[-1],d)
样品运行-
In [75]: np.random.seed(0)
...: a = np.random.randint(2, size=(5, 20))
In [76]: a
Out[76]:
array([[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0],
[0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0],
[0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0]])
In [77]: count_periodic_boundary(a)
Out[77]: array([7, 4, 5, 2, 6])
In [72]: np.random.seed(0)
...: a = np.random.randint(2, size=(2, 5, 20))
In [73]: a
Out[73]:
array([[[0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0],
[0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0],
[0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0]],
[[1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1],
[0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0]]])
In [74]: count_periodic_boundary(a)
Out[74]: array([7, 4, 5, 2, 6, 2, 5, 4, 2, 1])
这篇关于Python中具有周期性边界的数组中的连续值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!