我有福勒。数据帧:

datetime
2012-01-01    125.5010
2012-01-02    125.5010
2012-01-03    125.5010
2012-02-04    125.5010
2012-02-05    125.5010
2012-02-29    125.5010
2012-02-28    125.5010
2016-01-07    125.5010
2016-01-08    125.5010
2016-02-29     81.6237

我想删除2月29日对应的所有行,结果如下。数据帧:
datetime
2012-01-01    125.5010
2012-01-02    125.5010
2012-01-03    125.5010
2012-02-04    125.5010
2012-02-05    125.5010
2012-02-28    125.5010
2016-01-07    125.5010
2016-01-08    125.5010

现在,我只是手动操作:
df.drop(df.index[['2012-02-29']])我如何才能使它在所有年份都能工作,而不必手动指定行索引。

最佳答案

IIUC您可以屏蔽它并通过以下方式删除:

def is_leap_and_29Feb(s):
    return (s.index.year % 4 == 0) &
           ((s.index.year % 100 != 0) | (s.index.year % 400 == 0)) &
           (s.index.month == 2) & (s.index.day == 29)

mask = is_leap_and_29Feb(df)
print mask
#[False False False False False  True False False False  True]

print df.loc[~mask]
#            datetime
#2012-01-01   125.501
#2012-01-02   125.501
#2012-01-03   125.501
#2012-02-04   125.501
#2012-02-05   125.501
#2012-02-28   125.501
#2016-01-07   125.501
#2016-01-08   125.501

关于python - 从pandas数据框中删除闰年,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34966422/

10-12 22:24