![](/img/trans.png)
[英]Pandas: Get Business Month-End Dates Correctly Even for Dates Already on Month-End
[英]How to validate Pandas Dataframe column consist of month-end dates?
我有一个Pandas DF,它有一个称为ref_date
的列,该列由日期组成。 我想确认所有日期都是该月的最后一天。 我正在尝试以这种方式进行操作,但是它似乎并没有给我正确的结果,特别是df[ref_date].dt.is_month_end
部分没有给我正确的系列。
df[ref_date] = pd.to_datetime(df[ref_date])
month_end_dates = df[ref_date].dt.is_month_end
indices = np.where(month_end_dates == False)[0]
if indices.size > 0:
idx = indices[0]
raise ValidationError("The following date is not the end of a month: " + str(df[ref_date][idx].strftime('%m/%d/%Y')))
任何建议/帮助,不胜感激。
编辑:这是一个示例:
df(输出时):
ref_date regime_tag
0 2010-01-31 3
1 2010-02-28 2
2 2010-03-31 1
3 2010-04-30 2
4 2010-05-31 1
5 2010-06-30 1
6 2010-07-31 4
7 2010-08-31 1
8 2010-09-30 2
9 2010-10-29 4
10 2010-11-30 3
11 2010-12-31 3
month_end_dates(输出时):
0 False
1 False
2 True
3 True
4 True
5 True
6 False
7 True
8 True
9 True
10 True
11 True
这是不对的,因为2010年1月31日是一个月末,而2010年10月29日不是一个月末。
回答:
month_end_dates = df.ref_date + pd.offsets.MonthEnd(0) == df.ref_date
indices = np.where(month_end_dates == False)[0]
if indices.size > 0:
idx = indices[0]
raise ValidationError("The following date is not the end of a month: " + str(df[ref_date][idx].strftime('%m/%d/%Y')))
您可以使用pd.offsets.MonthEnd
df.ref_date + pd.offsets.MonthEnd(0) == df.ref_date
0 True
1 True
2 True
3 True
4 True
5 True
6 True
7 True
8 True
9 False
10 True
11 True
Name: ref_date, dtype: bool
我会建议
df.ref_date.apply(lambda x: True if x.is_month_end else False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.