gpt4 book ai didi

python - 如何在 numpy 数组中找到连续的正数、负数和零?

转载 作者:太空宇宙 更新时间:2023-11-03 13:54:50 25 4
gpt4 key购买 nike

我使用以下函数来查找连续的负数和正数,现在我还想添加一个条件来获取连续的零。我该怎么做?

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
# ...

关于python - 如何在 numpy 数组中找到连续的正数、负数和零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58013048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com