【发布时间】:2019-09-19 14:15:11
【问题描述】:
我使用以下函数来查找连续的负数和正数,现在我还想添加一个条件来获取连续的零。 我该怎么做?
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]))
谢谢:)
【问题讨论】:
-
你能放一个输入数据帧和预期输出的sn-p吗?
-
@SH-SF 当然,在这里。我做到了:)
标签: python arrays pandas numpy