python pandas dataframe slicing by date conditions

前端 未结 4 878
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 18:27

I am able to read and slice pandas dataframe using python datetime objects, however I am forced to use only existing dates in index. For example, this works:

4条回答
  •  伪装坚强ぢ
    2020-11-29 19:07

    I had difficulty with other approaches but I found that the following approach worked for me:

    # Set the Index to be the Date
    df['Date'] = pd.to_datetime(df['Date_1'], format='%d/%m/%Y')
    df.set_index('Date', inplace=True)
    
    # Sort the Data
    df = df.sort_values('Date_1')
    
    # Slice the Data
    From = '2017-05-07'
    To   = '2017-06-07'
    df_Z = df.loc[From:To,:]
    

提交回复
热议问题