python - 应用,lambda 函数问题
问题描述
我在声明中遇到问题,并使用带有该方法的函数if
返回两个日期之间的差异。当条件为 时,以纳秒为单位返回时间/天数。我的代码有什么问题?lambda
apply
['conus_days']
true
us_bd = CustomBusinessDay(calendar=USFederalHolidayCalendar())
def get_conusdays(row):
if row['Month']== row['conus_mth']:
return forecast['Start Date'] - forecast['start_month'].apply(us_bd)
else:
return 0
forecast ['conus_days']= forecast.apply(lambda row: get_conusdays(row), axis=1)
print(forecast)
Name EID Start Date End Date Country year Month \
0 XX 123456 2019-08-01 2020-01-03 AF 2020 1
1 XT. 3456789 2019-09-22 2020-02-16 Conus 2020 1
2 MH. 456789 2019-12-05 2020-03-12 Conus 2020 1
3 DR. 789456 2019-09-11 2020-03-04 IR 2020 1
4 JR. 985756 2020-01-03 2020-05-06 GE 2020 1
days_in_month start_month end_month working_days hours conus_mth \
0 31 2020-01-01 2020-01-31 21 372 8
1 31 2020-01-01 2020-01-31 21 168 9
2 31 2020-01-01 2020-01-31 21 168 12
3 31 2020-01-01 2020-01-31 21 372 9
4 31 2020-01-01 2020-01-31 21 310 1
cd conus_days
0 -154 days 0
1 -102 days 0
2 -28 days 0
3 -113 days 0
4 1 days [-13305600000000000 nanoseconds, -881280000000...
解决方案
这是因为get_conusdays
函数的返回是一个系列和一个值(0)。您需要将返回输出与系列或值统一起来。
你可以这样尝试:
1.np.where
forecast ['conus_days'] = np.where(forecast['Month']==forecast["conus_mth"],
forecast['Start Date'] - forecast['start_month'].apply(us_bd),
0)
添加。
start_date = pd.to_datetime('2020-01-03')
end_date = pd.to_datetime('2020-01-20')
print(len(pd.DatetimeIndex(start=start_date,end=end_date, freq=us_bd)))
>>> 12 #skip US holidays as well as weekends
所以,
forecast ['conus_days'] = np.where(forecast['Month']==forecast["conus_mth"],
forecast.apply(lambda row : len(pd.DatetimeIndex(start=row['end_moth'],end=row['End Date'], freq=us_bd)), axis=1),
0)
同样的问题:Python 中最近的前一个工作日
2.申请(你的方法)
def get_conusdays(row):
if row['Month']== row['conus_mth']:
return row['Start Date'] - row['start_month'].apply(us_bd)
else:
return 0
forecast['conus_days']= forecast.apply(lambda row: get_conusdays(row), axis=1)
如果您不确切知道CustomBusinessDay
并且不需要将其应用于系列,您应该这样做(每一行)。
推荐阅读
- python-3.x - 创建二维数组
- javascript - 转换为 ISOString 后返回日期/时间而不切片的另一种方法?
- python - 为什么在 Python 的 csv.DictReader 中计算 csvfile 的行数会破坏我的代码?
- python-3.x - 是否可以重载类型方法的返回?
- akka.net - 我可以将 Akka.Cluster.Sharding-1.3.13-beta 用于生产吗?
- python - Django 文件列表返回一个空数组
- python - 如何将从 rospy.Subscriber 数据中获得的数据输入到变量中?
- jquery - 如何从 JQUERY 迁移到 ReactJS
- azure - 如何使用逻辑应用向上/向下扩展 Azure SQL DW
- ios - 在将 NSString 转换为 String 时,我的结果发生了变化