Select DataFrame rows between two dates

前端 未结 10 696
挽巷
挽巷 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 03:57

    Another option, how to achieve this, is by using pandas.DataFrame.query() method. Let me show you an example on the following data frame called df.

    >>> df = pd.DataFrame(np.random.random((5, 1)), columns=['col_1'])
    >>> df['date'] = pd.date_range('2020-1-1', periods=5, freq='D')
    >>> print(df)
          col_1       date
    0  0.015198 2020-01-01
    1  0.638600 2020-01-02
    2  0.348485 2020-01-03
    3  0.247583 2020-01-04
    4  0.581835 2020-01-05
    

    As an argument, use the condition for filtering like this:

    >>> start_date, end_date = '2020-01-02', '2020-01-04'
    >>> print(df.query('date >= @start_date and date <= @end_date'))
          col_1       date
    1  0.244104 2020-01-02
    2  0.374775 2020-01-03
    3  0.510053 2020-01-04
    

    If you do not want to include boundaries, just change the condition like following:

    >>> print(df.query('date > @start_date and date < @end_date'))
          col_1       date
    2  0.374775 2020-01-03
    

提交回复
热议问题