【问题标题】:How to extract numeric ranges from 2 columns containig numeric sequences and print the range from both columns (different increment values)?如何从包含数字序列的 2 列中提取数字范围并打印两列的范围(不同的增量值)?
【发布时间】:2016-11-15 19:19:56
【问题描述】:

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

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

    1 
    2
    3
    5
    7
    8
    9

Col 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 的标准根据在两列上检测到的中断生成数字范围。

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

在这种情况下的独特区别在于,适用于两列的递增/递减标准对于每一列都不同。

【问题讨论】:

    标签: python pandas numpy dataframe group-by


    【解决方案1】:

    试试这个:

    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] 的增量/减量分组,对应Col1Col2

    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
    

    【讨论】:

    • 是否可以应用不同的数学函数来评估每一列的范围?例如 col1 >=8 和 col2
    • @A.ALT,您能否用可重现的样本数据集和所需的数据集打开一个新问题?
    猜你喜欢
    • 2017-03-19
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多