如何根据用作每列标准的数学运算从两列中提取数值范围?

2024-04-16 17:44:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在前面的问题(How to extract numeric ranges from 2 columns containig numeric sequences and print the range from both columns (different increment values)?)的基础上使用python的PANDAS数据帧;得到了以下问题:有没有一种方法可以使用PANDAS数据帧根据每列的不同数学运算创建数值范围?你知道吗

例如:

col1    col2   criteria-col1 diff. >2     criteria-col2 diff<=3                
1       23    abs(2-1)=1 ; no break     abs(27-23)=4;no break          
2       27    abs(4-2)=2 ; no break     abs(31-27)=4;no break
4       31    abs(6-4)=2;  no break     abs(35-31)=4;no break
6       35    abs(9-6)=3; break            abs(40-35)=5; no break but still break due to col1 criteria
9       40    abs(11-9)=2; no break    abs(45-40)=5;no break
11      45    abs(13-11)=2;no break    abs(49-45)=4;no break
13      49    abs (51-49)=2;no break   abs (51-49)=2; break also in column 1 due to critera in col2
15      51  

条件:创建数字范围,其中序列(升序或降序)由任何值>;2构成

条件:创建数值范围,其中数值序列(升序或降序)由任何值<;=3构成

预期结果应为序列根据上述标准中断的范围:

col1_from  col1_to   col2_from  col2_to
        1        6          23       35
        9       13          40       49
       15       15          51       51

Tags: columnsto数据nofrompandasdiff序列
1条回答
网友
1楼 · 发布于 2024-04-16 17:44:41

数据:

In [10]: df
Out[10]:
   col1  col2
0     1    23
1     2    27
2     4    31
3     6    35
4     9    40
5    11    45
6    13    49
7    15    51

解决方案:

In [11]: df.groupby(df.diff().abs().eval("col1 > 2 or col2 <= 3").cumsum()) \
           .agg(['min','max'])
Out[11]:
  col1     col2
   min max  min max
0    1   6   23  35
1    9  13   40  49
2   15  15   51  51

说明:

In [12]: df.diff()
Out[12]:
   col1  col2
0   NaN   NaN
1   1.0   4.0
2   2.0   4.0
3   2.0   4.0
4   3.0   5.0
5   2.0   5.0
6   2.0   4.0
7   2.0   2.0

In [13]: df.diff().abs().eval("col1 > 2 or col2 <= 3")
Out[13]:
0    False
1    False
2    False
3    False
4     True
5    False
6    False
7     True
dtype: bool

In [14]: df.diff().abs().eval("col1 > 2 or col2 <= 3").cumsum()
Out[14]:
0    0
1    0
2    0
3    0
4    1
5    1
6    1
7    2
dtype: int32

相关问题 更多 >