python - Pandas 数据帧 : Delete specific date in all leap years

标签 python select pandas leap-year

以下序列是我获得的 pandas DataFrame 的摘录:

>>> df_t
              value
2011-01-31    -5.575000
2011-03-31     7.700000
2011-05-31    15.966667
2011-07-31    10.683333
2011-08-31    10.454167
2011-10-31     9.320833
2011-12-31    -0.358333
2012-01-31   -11.550000
2012-03-31     1.700000
2012-05-31    12.333333
2012-07-31    12.816667
2012-08-31    11.837500
2012-10-31     2.733333
2012-12-31     4.075000
2013-01-31     2.450000
2013-03-31    -4.262500
2013-05-31    11.491667
2013-07-31    14.812500
2013-08-31    13.920833
2013-10-31     4.125000
2013-12-31     0.075000 

如何删除闰年的 3 月 31 日? 我尝试过类似的事情:

def isleap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

if isleap(df_t.index.year):
        df_t=df_t[df_t.index.dayofyear!=91]

...但显然,这在我看来太简单了。循环整个数据框并在每一步检查年份是否是闰年并且日期是一年中的第 91 天是唯一的解决方案吗?还是有更简单的解决方案可用?

编辑:问题不在于如何确定一年是否为闰年,而是如果是,则删除上述数据框中的 3 月 31 日。

最佳答案

这是一个以矢量化方式执行此操作的示例。您应注意,andor 不适合 bool 值向量,请使用 &| 代替。

import pandas as pd
import numpy as np

s = pd.Series(np.random.randn(600), index=pd.date_range('1990-01-01', periods=600, freq='M'))

Out[76]: 
1990-01-31   -0.7594
1990-02-28   -0.1311
1990-03-31    1.2031
1990-04-30    1.1999
1990-05-31   -2.4399
               ...  
2039-08-31   -0.3554
2039-09-30   -0.3265
2039-10-31   -0.3832
2039-11-30   -1.4139
2039-12-31   -0.3086
Freq: M, dtype: float64


def is_leap_and_MarchEnd(s):
    return (s.index.year % 4 == 0) & ((s.index.year % 100 != 0) | (s.index.year % 400 == 0)) & (s.index.month == 3) & (s.index.day == 31)

mask = is_leap_and_MarchEnd(s)
s[mask]
Out[77]: 
1992-03-31    0.7834
1996-03-31    0.3121
2000-03-31   -1.2050
2004-03-31    0.6017
2008-03-31    0.1045
               ...  
2020-03-31    1.1037
2024-03-31    0.5139
2028-03-31   -0.8116
2032-03-31   -0.6939
2036-03-31   -1.1999
dtype: float64

# do delete these row
s[~mask]

关于python - Pandas 数据帧 : Delete specific date in all leap years,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30997007/

相关文章:

python - 将单索引数据框添加到多索引数据框、Pandas、Python

python - 前缀和算法

python - 如何删除目录中的所有文件,保持子目录完好无损

mysql - 将 IF 条件变量放在 SQL select 的 where 子句中

mysql - 如果条件大于返回值,则选择上一条记录

python - 将 python 列表转换为数据帧时,ValueError : 4 columns passed, 传递的数据有 3 列。如果3通过了如何添加空白值?

python - 使用 pandas 中的查询函数返回位于两个列表交集的行

python - 如何限制 python Holoviews 中的缩放最小和最大范围?

python - 使用带有\number 的组时出现 re.sub 问题

mysql - 插入带有来自 Select 的值的查询