Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter certain column by year

I have data that I am grouping by and after that I want to filter it by current year.

df['PERIOD'] = pd.to_datetime(df['PERIOD'], format='%Y%m', errors='coerce').dt.strftime('%Y/%m')
groupedResult = df.groupby('PERIOD', dropna=True)['ACTUALS'].sum().reset_index()

I have tried to add this line

groupedResult = groupedResult[groupedResult['PERIOD'].dt.year == datetime.today().year]

but getting

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

AttributeError: Can only use .dt accessor with datetimelike values

What I am doing wrong?

Example dataset:

import pandas as pd

data = {'PERIOD':['202201','202201','202201','202201','202202','202202','202203'], 'ACTUALS':[10,20,30,40,50,60,70]}
    
df = pd.DataFrame(data)
print("BEFORE:")

>Solution :

What I am doing wrong?

Here

df['PERIOD'] = pd.to_datetime(df['PERIOD'], format='%Y%m', errors='coerce').dt.strftime('%Y/%m')

you are converting PERIOD which is string to datetimelike, which is in turn converted (formatted) into string, thus you

AttributeError: Can only use .dt accessor with datetimelike values

as PERIOD hold string at that moment.

Consider converting PERIOD into datetime-like without further conversion into string. You might find pd.Grouper useful for this task, consider following example which calculate sum of ACTUAL for each Month (freq='M')

import pandas as pd

data = {'PERIOD':['202201','202201','202201','202201','202202','202202','202203'], 'ACTUALS':[10,20,30,40,50,60,70]}
    
df = pd.DataFrame(data)
df['PERIOD'] = pd.to_datetime(df['PERIOD'],format='%Y%m')
df.set_index('PERIOD', inplace=True)
total = df.groupby(pd.Grouper(freq='M')).sum()
print(total)

output

            ACTUALS
PERIOD
2022-01-31      100
2022-02-28      110
2022-03-31       70
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading