I would like to get total days based on Year column in Totaldays column.
df_date=pd.date_range(start ='12-31-2021', end ='12-31-2026', freq ='M')
df_date1=pd.DataFrame(df_date)
df_date1['daysinmonth'] = df_date1[0].dt.daysinmonth
df_date1['year'] = df_date1[0].dt.year
df_date1['Totaldays']=?
df_date1
0 daysinmonth Year Totaldays
0 2021-12-31 31 2021 365
1 2022-01-31 31 2022 365
2 2022-02-28 28 2022 365
3 2022-03-31 31 2022 365
4 2022-04-30 30 2022 365
>Solution :
You can use pd.Series.dt.is_leap_year for that:
import numpy as np
import pandas as pd
df['date'] = pd.DataFrame({'date': pd.date_range('1999-01-01', '2022-01-01', freq='1y')})
df['total_days'] = np.where(df['date'].dt.is_leap_year, 366, 365)
print(df)
date total_days
0 1999-12-31 365
1 2000-12-31 366
2 2001-12-31 365
3 2002-12-31 365
4 2003-12-31 365
5 2004-12-31 366
6 2005-12-31 365
7 2006-12-31 365
8 2007-12-31 365
9 2008-12-31 366
10 2009-12-31 365
11 2010-12-31 365
12 2011-12-31 365
13 2012-12-31 366
14 2013-12-31 365
15 2014-12-31 365
16 2015-12-31 365
17 2016-12-31 366
18 2017-12-31 365
19 2018-12-31 365
20 2019-12-31 365
21 2020-12-31 366
22 2021-12-31 365
Caveat: this will only work assuming the gregorian calendar is valid for these years. E.g. not in years where countries switched from Julian to Gregorian calendar (1752 in the UK, 1918 in Russia, …).