【问题标题】:How to find consecutive positive, negative and zeroes in a numpy array?如何在 numpy 数组中找到连续的正、负和零?
【发布时间】: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


【解决方案1】:

由于您标记了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
# ...

【讨论】:

  • 它是如何工作的?我的数组中有 288 个零,但它显示的不止这些。你能解释一下吗?
  • 我不确定我是否遵循。每个连续的零块被计为一个块。但是,代码不假设显示哪个块为零。
【解决方案2】:

这是一个 numpy 方法:

# 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])]

【讨论】:

  • 似乎是一个很好的方法,但我收到以下错误TypeError: diff() got an unexpected keyword argument 'prepend'
  • @daryushshiri 这是对 api 的一个相对较新的补充。您可以使用 np.diff(np.concatenate([[a],x,[b]])) 而不是 np.diff(x,prepend=a,append=b) 解决它
猜你喜欢
  • 2014-09-13
  • 2021-08-07
  • 2016-05-18
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多