Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas date index: select the first element of each month

I have a pandas data frame with dates as indices. For example:

            B group
index                  
2018-08-19     True
2018-08-20     True
2018-09-15     False
2018-09-15     False
2019-04-28     True
2019-06-01     False
2019-06-08     True

I want to select just the first element of each available month. For example in this DF I want to select these:

            B group
index                  
2018-08-19     True
2018-09-15     False
2019-04-28     True
2019-06-01     False

I have no idea how to do that. so I'm here to ask. Thanks in advance.

like image 306
Peyman Avatar asked Oct 18 '25 16:10

Peyman


1 Answers

Convert DatetimeIndex to month periods by DatetimeIndex.to_period and then filter by Series.duplicated with inverted mask and boolean indexing:

df = df[~df.index.to_period('m').duplicated()]
print (df)
            B group
2018-08-19     True
2018-09-15    False
2019-04-28     True
2019-06-01    False
like image 155
jezrael Avatar answered Oct 20 '25 16:10

jezrael