我使用以下函数来查找连续的负数和正数,现在我还想添加一个条件来获取连续的零。我该怎么做?
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
这是 Pandas 系列:
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]))
谢谢:)
由于您标记了 pandas
,所以这里有一种方法:
# random data
np.random.seed(1)
a = np.random.choice(range(-2,3), 1000)
# np.sign: + = 1, 0 = 0, - = -1
b = pd.Series(np.sign(a))
# b.head()
# 0 1
# 1 1
# 2 -1
# 3 -1
# 4 1
# dtype: int32
# sign blocks
blks = b.diff().ne(0).cumsum()
# blks.head()
# 0 1
# 1 1
# 2 2
# 3 2
# 4 3
# dtype: int32
# number of blocks:
blks.iloc[-1]
# 654
# block counts:
blks.value_counts()
# 1 2
# 2 2
# 3 1
# 4 3
# 5 2
# ...
我是一名优秀的程序员,十分优秀!