【问题标题】:Pandas: Total number of days in an year熊猫:一年中的总天数
【发布时间】:2022-01-24 15:41:11
【问题描述】:

我想根据 Totaldays 列中的 Year 列获取总天数。

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

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以为此使用pd.Series.dt.is_leap_year

    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
    

    警告:这仅在公历在这些年份有效的情况下才有效。例如。不是在国家从儒略历改为公历的年份(英国 1752 年,俄罗斯 1918 年......)。

    【讨论】:

      猜你喜欢
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2013-07-16
      • 2020-03-28
      • 2021-04-24
      • 2020-10-06
      相关资源
      最近更新 更多