Filtering Pandas DataFrames on dates

前端 未结 12 1237
时光取名叫无心
时光取名叫无心 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:39

    So when loading the csv data file, we'll need to set the date column as index now as below, in order to filter data based on a range of dates. This was not needed for the now deprecated method: pd.DataFrame.from_csv().

    If you just want to show the data for two months from Jan to Feb, e.g. 2020-01-01 to 2020-02-29, you can do so:

    import pandas as pd
    mydata = pd.read_csv('mydata.csv',index_col='date') # or its index number, e.g. index_col=[0]
    mydata['2020-01-01':'2020-02-29'] # will pull all the columns
    #if just need one column, e.g. Cost, can be done:
    mydata['2020-01-01':'2020-02-29','Cost'] 
    

    This has been tested working for Python 3.7. Hope you will find this useful.

提交回复
热议问题