大熊猫根据条件和时间戳序列对数据帧进行切片

时间:2019-02-27 01:59:03

标签: python pandas

当列A> 1且增量时间戳记超过2天时,我想将Label列添加到数据框中

Time              A          Label
2019-02-1        0.1          
2019-02-2        1.1
2019-02-3        0.2
2019-02-4        0.3
2019-02-5        1.1          
2019-02-6        1.1          
2019-02-7        2.1          
2019-02-8        0.4
2019-02-9        0.5
2019-02-10       1.6          
2019-02-11       1.7          
2019-02-12       2.1          
2019-02-13       4.4          
2019-02-14       0.5

结果应该是

Time              A           Label
2019-02-1        0.1          False
2019-02-2        1.1          False
2019-02-3        0.2          False
2019-02-4        0.3          False
2019-02-5        1.1          True
2019-02-6        1.1          True
2019-02-7        2.1          True
2019-02-8        0.4          False
2019-02-9        0.5          False
2019-02-10       1.6          True
2019-02-11       1.7          True
2019-02-12       2.1          True
2019-02-13       4.4          True
2019-02-14       0.5          False

以及如何根据“标签”列获取时间范围

1 个答案:

答案 0 :(得分:1)

使用cumsum创建groupby键,然后可以使用transform

g = df.loc[df.A.ge(1),'Time'].groupby(df.A.le(1).cumsum())
df['Label']=(g.transform('last')-g.transform('first')).dt.days>1
df.Label=df.Label.fillna(False)
df
         Time    A  Label
0  2019-02-01  0.1  False
1  2019-02-02  1.1  False
2  2019-02-03  0.2  False
3  2019-02-04  0.3  False
4  2019-02-05  1.1   True
5  2019-02-06  1.1   True
6  2019-02-07  2.1   True
7  2019-02-08  0.4  False
8  2019-02-09  0.5  False
9  2019-02-10  1.6   True
10 2019-02-11  1.7   True
11 2019-02-12  2.1   True
12 2019-02-13  4.4   True
13 2019-02-14  0.5  False
相关问题