Search code examples
pandastime-seriesyfinancepandas-timeindex

Best way to filter out data from specific month in pandas


I have financial data:

                  Open        High  ...   Adj Close    Volume
Date                                ...                      
2016-11-17   60.410000   60.950001  ...   56.484898  32132700
2016-11-18   60.779999   61.139999  ...   56.214767  27686300
2016-11-21   60.500000   60.970001  ...   56.689823  19652600
2016-11-22   60.980000   61.259998  ...   56.932003  23206700
2016-11-23   61.009998   61.099998  ...   56.261349  21848900
                ...         ...  ...         ...       ...
2021-11-10  334.570007  334.630005  ...  330.799988  25500900
2021-11-11  331.250000  333.769989  ...  332.429993  16849800
2021-11-12  333.920013  337.230011  ...  336.720001  23822000
2021-11-15  337.540009  337.880005  ...  336.070007  16723000
2021-11-16  335.679993  340.670013  ...  339.510010  20746300

I want to filter out all the examples in a specific month, e.g., November. To clarify, I want data from each November, regardless of the year.

I guess I could reset the index and than extract the month somehow.

Is there an easier way?, like between_time offers the option to filter out intra-day time intervals.


Solution

  • Assuming you have a DatetimeIndex, use dt accessor.

    df_nov = df[df.index.month == 11]