Select DataFrame rows between two dates

前端 未结 10 871
挽巷
挽巷 2020-11-22 03:14

I am creating a DataFrame from a csv as follows:

stock = pd.read_csv(\'data_in/\' + filename + \'.csv\', skipinitialspace=True)

The DataFra

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 04:01

    I prefer not to alter the df.

    An option is to retrieve the index of the start and end dates:

    import numpy as np   
    import pandas as pd
    
    #Dummy DataFrame
    df = pd.DataFrame(np.random.random((30, 3)))
    df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')
    
    #Get the index of the start and end dates respectively
    start = df[df['date']=='2017-01-07'].index[0]
    end = df[df['date']=='2017-01-14'].index[0]
    
    #Show the sliced df (from 2017-01-07 to 2017-01-14)
    df.loc[start:end]
    

    which results in:

         0   1   2       date
    6  0.5 0.8 0.8 2017-01-07
    7  0.0 0.7 0.3 2017-01-08
    8  0.8 0.9 0.0 2017-01-09
    9  0.0 0.2 1.0 2017-01-10
    10 0.6 0.1 0.9 2017-01-11
    11 0.5 0.3 0.9 2017-01-12
    12 0.5 0.4 0.3 2017-01-13
    13 0.4 0.9 0.9 2017-01-14
    

提交回复
热议问题