Pandas DataFrame: Delete specific date in all leap years

我的未来我决定 提交于 2019-12-06 10:21:27

Here is an example to do that in a vectorized way. You shall note that and and or are not appropriate for a vector of booleans, use & and | instead.

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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!