【问题标题】:Reduce column values for leap years in pandas dataframe减少熊猫数据框中闰年的列值
【发布时间】:2015-10-05 03:49:32
【问题描述】:

我有一个类似的数据框。形式:

datetime       JD      YEAR
2000-01-01      1      2000
2000-01-02      2      2000
2000-01-03      3      2000
2000-01-04      4      2000
2000-01-05      5      2000
2000-01-06      6      2000
2000-01-07      7      2000
2000-01-08      8      2000
2000-01-09      9      2000
...
2010-12-31      365    2014

JD 值是儒略日,即它从每年 1 月 1 日的 1 开始(闰年最高为 366,其他年份最高为 365)。我想从每个闰年的 2 月 29 日开始的每一天将 JD 值减少 1。非闰年不应更改 JD 值。这是我现在正在做的事情:

def reduce_JD(row):
    if calendar.isleap(row.YEAR) & row.JD > 59:
        row.JD = row.JD - 1

    return row

def remove_leap_JD(df):
    # Reduce JD by 1 for each day following Feb 29th
    df.apply(reduce_JD, axis=1)

    return df

pdf = remove_leap_JD(pdf)

但是,我没有看到闰年的 JD 值有任何变化。我做错了什么?

--编辑: datetime 是索引列

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    有两个问题:

    1. reduce_JD() 中,应使用and 而不是&。否则,由于运算符优先级,条件df.iloc[59].JD > 59 的第二部分应加括号。请注意:

      calendar.isleap(df.iloc[59].YEAR) & (df.iloc[59].JD > 59)
      # True
      calendar.isleap(df.iloc[59].YEAR) & df.iloc[59].JD > 59
      # False!
      
    2. apply 函数返回一个新的 DataFrame,而不是就地修改输入。因此,remove_leap_JD() 中的代码应改为:

      df = df.apply(reduce_JD, axis=1)
      

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 2021-12-18
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 2020-07-06
      • 1970-01-01
      • 2016-08-14
      相关资源
      最近更新 更多