Filtering Pandas DataFrames on dates

前端 未结 12 1077
时光取名叫无心
时光取名叫无心 2020-11-22 16:15

I have a Pandas DataFrame with a \'date\' column. Now I need to filter out all rows in the DataFrame that have dates outside of the next two months. Essentially, I only need

12条回答
  •  名媛妹妹
    2020-11-22 16:34

    You can use pd.Timestamp to perform a query and a local reference

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame()
    ts = pd.Timestamp
    
    df['date'] = np.array(np.arange(10) + datetime.now().timestamp(), dtype='M8[s]')
    
    print(df)
    print(df.query('date > @ts("20190515T071320")')
    

    with the output

                     date
    0 2019-05-15 07:13:16
    1 2019-05-15 07:13:17
    2 2019-05-15 07:13:18
    3 2019-05-15 07:13:19
    4 2019-05-15 07:13:20
    5 2019-05-15 07:13:21
    6 2019-05-15 07:13:22
    7 2019-05-15 07:13:23
    8 2019-05-15 07:13:24
    9 2019-05-15 07:13:25
    
    
                     date
    5 2019-05-15 07:13:21
    6 2019-05-15 07:13:22
    7 2019-05-15 07:13:23
    8 2019-05-15 07:13:24
    9 2019-05-15 07:13:25
    

    Have a look at the pandas documentation for DataFrame.query, specifically the mention about the local variabile referenced udsing @ prefix. In this case we reference pd.Timestamp using the local alias ts to be able to supply a timestamp string

提交回复
热议问题