【问题标题】:filter and extend time-series pandas dataframe过滤和扩展时间序列 pandas 数据框
【发布时间】:2020-04-29 21:54:19
【问题描述】:

这个问题是这个问题的补充:filter multi-indexed grouped pandas dataframe

我想得到timestamp,其中valuedate之后开始大于零,作为每个人id的新列new_date

示例输入数据:

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

想要的输出数据示例:

id timestamp  date       value new_date
1  2001-01-01 2001-05-01 1     2001-10-02
1  2001-10-01 2001-05-01 0     2001-10-02
1  2001-10-02 2001-05-01 1     2001-10-02
1  2001-10-03 2001-05-01 0     2001-10-02
1  2001-10-04 2001-05-01 1     2001-10-02
2  2001-01-01 2001-05-01 1     2001-10-04
2  2001-10-01 2001-05-01 0     2001-10-04
2  2001-10-02 2001-05-01 0     2001-10-04
2  2001-10-03 2001-05-01 0     2001-10-04
2  2001-10-04 2001-05-01 1     2001-10-04

【问题讨论】:

    标签: python pandas time-series filtering


    【解决方案1】:

    如果某些组没有匹配项,也可以使用更简单的解决方案,首先过滤 DataFrame 链式掩码以获得更大的类似 Series.gtdate 和按位 AND0 相同,然后通过 DataFrame.drop_duplicates 删除重复项,创建Series,最后使用Series.map

    df['timestamp'] = pd.to_datetime(df['timestamp'])
    df['date'] = pd.to_datetime(df['date'])
    df = df.sort_values(['id','timestamp'])
    
    m = df['timestamp'].gt(df['date']) & df['value'].gt(0)
    
    s = df[m].drop_duplicates('id').set_index('id')['timestamp']
    
    df['new_date'] = df['id'].map(s)
    print (df)
       id  timestamp       date  value   new_date
    0   1 2001-01-01 2001-05-01      1 2001-10-02
    1   1 2001-10-01 2001-05-01      0 2001-10-02
    2   1 2001-10-02 2001-05-01      1 2001-10-02
    3   1 2001-10-03 2001-05-01      0 2001-10-02
    4   1 2001-10-04 2001-05-01      1 2001-10-02
    5   2 2001-01-01 2001-05-01      1 2001-10-04
    6   2 2001-10-01 2001-05-01      0 2001-10-04
    7   2 2001-10-02 2001-05-01      0 2001-10-04
    8   2 2001-10-03 2001-05-01      0 2001-10-04
    9   2 2001-10-04 2001-05-01      1 2001-10-04
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 2017-11-03
      • 1970-01-01
      • 2019-06-18
      • 2018-06-07
      • 1970-01-01
      相关资源
      最近更新 更多