我使用下面的函数来查找连续的负数和正数,现在我还想添加一个条件来获得连续的零。
我该怎么做?
def consecutive_counts(arr):
'''
Returns number of consecutive negative and positive numbers
arr = np.array
negative = consecutive_counts()[0]
positive = consecutive_counts()[1]
'''
pos = arr > 0
# is used to Compute indices that are non-zero in the flattened version of arr
idx = np.flatnonzero(pos[1:] != pos[:-1])
count = np.concatenate(([idx[0]+1], idx[1:] - idx[:-1], [arr.size-1-idx[-1]]))
negative = count[1::2], count[::2]
positive = count[::2], count[1::2]
if arr[0] < 0:
return negative
else:
return positive
这是熊猫系列:
In [221]: n.temp.p['50000']
Out[221]:
name
0 0.00
1 -92.87
2 -24.01
3 -92.87
4 -92.87
5 -92.87
... ...
我是这样用的:
arr = n.temp.p['50000'].values #Will be a numpy array as the input
预期产量:
In [225]: consecutive_counts(a)
Out[225]: (array([30, 29, 11, ..., 2, 1, 3]), array([19, 1, 1, ..., 1, 1, 2]))
谢谢:)
最佳答案
下面是一个新方法:
# create example
arr = np.random.randint(-2,3,(10))
# split into negative, zero, positive
*nzp, = map(np.flatnonzero,(arr<0,arr==0,arr>0))
# find block boundaries
*bb, = (np.flatnonzero(np.diff(x,prepend=-2,append=-2)-1) for x in nzp)
# compute block sizes
*bs, = map(np.diff,bb)
# show all
for data in (arr,nzp,bb,bs): print(data)
# [-1 1 -1 1 0 0 2 -1 -2 1]
# [array([0, 2, 7, 8]), array([4, 5]), array([1, 3, 6, 9])]
# [array([0, 1, 2, 4]), array([0, 2]), array([0, 1, 2, 3, 4])]
# [array([1, 1, 2]), array([2]), array([1, 1, 1, 1])]
关于python - 如何在numpy数组中找到连续的正数,负数和零?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58013048/