Peyman
Peyman

Reputation: 4179

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.

Upvotes: 4

Views: 1129

Answers (1)

jezrael
jezrael

Reputation: 862491

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

Upvotes: 6

Related Questions