Flying pig
Flying pig

Reputation: 612

How to extract a specific month and day from all the years in Pandas?

My dataset looks like this

            CPI
DATE    
1950-01-01  NaN
1950-02-01  1.004254
1950-03-01  1.005530
1950-04-01  1.005955
1950-05-01  1.011059
... ...
2020-01-01  1.001455
2020-02-01  1.002345
2020-03-01  0.998100
2020-04-01  0.990164
2020-05-01  0.989646

I would like to extract all the data from 'XXXX-01-01' in every year. And put them into a new data set. Could anyone make an example how to do this?

Upvotes: 1

Views: 1007

Answers (2)

Dishin H Goyani
Dishin H Goyani

Reputation: 7693

You can use query also

df.query("index.dt.month.eq(1) and index.dt.day.eq(1)")

Assuming you have index of Datetimeindex type if not first convert it Datetimeindex using df.index = pd.to_datetime(df.index)

Upvotes: 0

ScootCork
ScootCork

Reputation: 3676

You can try:

new_df = df.loc[(df.DATE.dt.month == 1) & (df.DATE.dt.day == 1)]

Upvotes: 2

Related Questions