filter multi-indexed grouped pandas dataframe

前端 未结 1 453
囚心锁ツ
囚心锁ツ 2021-01-25 06:37

The data looks like the following:

id  timestamp   date        value
1   2001-01-01  2001-05-01  0
1   2001-10-01  2001-05-01  1
2   2001-01-01          


        
相关标签:
1条回答
  • 2021-01-25 06:51

    For get all ids by 1 in value column and also timestamp are higher like date create 2 masks by Series.gt, chain by & for bitwise AND and then test if at least one True per group by GroupBy.any and GroupBy.transform:

    df['timestamp'] = pd.to_datetime(df['timestamp'])
    df['date'] = pd.to_datetime(df['date'])
    df = df.sort_values(['id','timestamp'])
    
    m = df['value'].gt(0) & df['timestamp'].gt(df['date'])
    df = df[m.groupby(df['id']).transform('any')]
    print (df)
       id  timestamp       date  value
    0   1 2001-01-01 2001-01-05      0
    1   1 2001-01-10 2001-01-05      1
    
    0 讨论(0)
提交回复
热议问题