如何从2列中提取数字范围包含数字序列并从两列中打印范围(不同的增量值)?

时间:2016-11-15 10:40:31

标签: python pandas numpy dataframe group-by

我非常熟悉了学习python和pandas(这个问题基于一个明显的帖子,但有一个额外的查询);目前有2列包含数字序列(升序和/或降序),如下所述:

Col 1 :( col1数字增量和/或减量= 1)

    1 
    2
    3
    5
    7
    8
    9

第2栏:( Col2数字增量和/或减量= 4)

 113
 109
 105
 90
 94
 98
 102

需要从两列中提取数值范围并根据这两列中任何一列的序列中断出现打印它们,结果应如下所示:

 1,3,105,113
 5,5,90,90
 7,9,94,102

已经收到了一个非常有用的方法来使用@MaxU的python的pandas库,它使用col1和col2 =增加和/或减少1的标准,根据在两列上检测到的中断生成数值范围。 / p>

How can I extract numeric ranges from 2 columns and print the range from both columns as tuples?

这种情况的唯一区别在于,对于每一列,应用于两列的递增/递减标准是不同的。

1 个答案:

答案 0 :(得分:3)

试试这个:

In [42]: df
Out[42]:
   Col1  Col2
0     1   113
1     2   109
2     3   105
3     5    90
4     7    94
5     8    98
6     9   102

In [43]: df.groupby(df.diff().abs().ne([1,4]).any(1).cumsum()).agg(['min','max'])
Out[43]:
  Col1     Col2
   min max  min  max
1    1   3  105  113
2    5   5   90   90
3    7   9   94  102

解释:我们的目标是对[1,4]Col1的增量/减量Col2进行相应的分组:

In [44]: df.diff().abs()
Out[44]:
   Col1  Col2
0   NaN   NaN
1   1.0   4.0
2   1.0   4.0
3   2.0  15.0
4   2.0   4.0
5   1.0   4.0
6   1.0   4.0

In [45]: df.diff().abs().ne([1,4])
Out[45]:
    Col1   Col2
0   True   True
1  False  False
2  False  False
3   True   True
4   True  False
5  False  False
6  False  False

In [46]: df.diff().abs().ne([1,4]).any(1)
Out[46]:
0     True
1    False
2    False
3     True
4     True
5    False
6    False
dtype: bool

In [47]: df.diff().abs().ne([1,4]).any(1).cumsum()
Out[47]:
0    1
1    1
2    1
3    2
4    3
5    3
6    3
dtype: int32
相关问题