给定值数组,我希望 Select 满足条件的多个连续元素序列.结果应该是每个元素序列对应一个array.

For example I have an array containing both negative and positive numbers. I need to select sequences of negative numbers, with each sequence in a separate array.
Here is an example :

import numpy as np

# Example data
values = np.array([1, 2, 3, -1, -2, -3, 4, 5, 6, -7, -8, 10])

mask = values < 0

下面是输出应该是什么样子:

Array 1:

[-1 -2 -3]

Array 2:

[-7 -8]

我试着用numpy.split来做这件事,但它变得更像意大利面代码.我想知道有没有一种毕达德式的方法来完成这项任务?

推荐答案

clustering groups of negative numbers

如果您只想对负值的块进行分组,而不考虑它们的相对值,那么只需计算第二个掩码来标识每个负值块的开始:

mask = values < 0
mask2 = np.r_[True, np.diff(mask)]
out = np.array_split(values[mask], np.nonzero(mask2[mask])[0][1:])

输出:[array([-1, -7, -3]), array([-7, -8])]

clustering groups of negative numbers if they are successive in value

If you want to cluster the negative values that also a successively decreasing (e.g. -1, -2, -3, -5, -6 would form 2 clusters: -1, -2, -3 and -5, -6. Then I would use :

  • 转换为Series
  • 找出负值
  • 为连续的负值创建分组((~mask).cumsum())
  • 添加索引(或范围)以对连续的
  • groupby
import pandas as pd

s = pd.Series(values)

# mask to keep negative values
mask = s<0
# group consecutive negatives
group1 = (~mask).cumsum()
# group successive decrementing values
s2 = s+s.index
group2 = s2.ne(s2.shift()).cumsum()

out = [g.to_numpy() for k, g in s[mask].groupby([group1, group2])]

输出:[array([-1, -2, -3]), array([-7, -8]), array([-7])]

中间体:

     s   mask  s2  group1  group2
0    1  False   1       1       1
1    2  False   3       2       2
2    3  False   5       3       3
3   -1   True   2       3       4 # out 1
4   -2   True   2       3       4 #
5   -3   True   2       3       4 #
6    4  False  10       4       5
7    5  False  12       5       6
8    6  False  14       6       7
9   -7   True   2       6       8  # out 2 
10  -8   True   2       6       8  #
11  -7   True   4       6       9    # out 3
12  10  False  22       7      10

Python相关问答推荐

运行回文查找器代码时发生错误:[类型错误:builtin_index_or_system对象不可订阅]

pandas DataFrame GroupBy.diff函数的意外输出

_repr_html_实现自定义__getattr_时未显示

按列分区,按另一列排序

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

pandas滚动和窗口中有效观察的最大数量

对所有子图应用相同的轴格式

实现自定义QWidgets作为QTimeEdit的弹出窗口

将输入聚合到统一词典中

python中的解释会在后台调用函数吗?

Flash只从html表单中获取一个值

幂集,其中每个元素可以是正或负""""

手动设置seborn/matplotlib散点图连续变量图例中显示的值

matplotlib图中的复杂箭头形状

在方法中设置属性值时,如何处理语句不可达[Unreacable]";的问题?

Gekko中基于时间的间隔约束

如果有2个或3个,则从pandas列中删除空格

从一个df列提取单词,分配给另一个列

Python:从目录内的文件导入目录

如何在Python中实现高效地支持字典和堆操作的缓存?