user308827
user308827

Reputation: 21971

Extracting subset of pandas dataframe based on months

I have the foll. pandas dataframe (df with a datetime index):

datetime    Year    cal val
1/1/2000    2000    1   0.23
1/2/2000    2000    1   0.34
2/3/2000    2000    1   0.45
4/4/2000    2000    2   0.56
4/5/2000    2000    2   0.67
4/6/2000    2000    2   0.78
5/7/2000    2000    3   0.89
7/8/2000    2000    3   1
7/9/2000    2000    3   1.11

How can I extract those rows which correspond to months from a list:

list_months = [1, 2]

Resulting dataframe will be:

datetime    Year    cal val
1/1/2000    2000    1   0.23
1/2/2000    2000    1   0.34

I tried this, but it does not work:

[x for x in df if df.index.month in list_months]

Upvotes: 2

Views: 1048

Answers (1)

jezrael
jezrael

Reputation: 862661

Maybe you can use index.to_series and isin:

print df[df.index.to_series().dt.month.isin(list_months)]
            Year  cal   val
datetime                   
2000-01-01  2000    1  0.23
2000-02-01  2000    1  0.34

Upvotes: 4

Related Questions