'How to select an index containing specific characters?

I have the following dataframe:

cov_afro

My goal is to plot the evolution of new covid 19 cases during april in Africa (WHO_region = AFRO). In order to do that, I create the following pivot table:

cov_afro_tab = cov_afro.pivot_table('New_cases', index='Date_reported', aggfunc= "sum")

cov_afro_tab

How can I filter index containing only "2022-04"?

Thank you for your help!



Solution 1:[1]

Convert the index to datetime type and check if the year and month is equal to threshold.

df.index = pd.to_datetime(df.index)

df_ = df[df.index.strftime('%Y-%m') == '2022-04']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ynjxsjmh