在Pandas中计算两个日期之间的有效天数。

huangapple go评论69阅读模式
英文:

Efficient days between two dates in Pandas

问题

works

pre_start['exposure_days'] = (datetime.now() - pd.to_datetime(pre_start['First_Exposure']))

doesn't work

pre_start['exposure_days'] = (datetime.now() - pd.to_datetime(pre_start['First_Receive_Date'])).days

我得到的错误是`AttributeError: 'Series' object has no attribute 'days'`。

除了像这样做一些繁琐和低效的事情
`pre_start['real_exposure_days'] = pre_start['exposure_days'].apply(lambda x: x.days)`,是否有一种绕过此错误获取天数的方法?

<details>
<summary>英文:</summary>

```python
# works
pre_start[&#39;exposure_days&#39;] = (datetime.now() - pd.to_datetime(pre_start[&#39;First_Exposure&#39;]))

# doesn&#39;t work
pre_start[&#39;exposure_days&#39;] = (datetime.now() - pd.to_datetime(pre_start[&#39;First_Receive_Date&#39;])).days

The error I get is AttributeError: &#39;Series&#39; object has no attribute &#39;days&#39;.

Without doing something obnoxious and inefficient like
pre_start[&#39;real_exposure_days&#39;] = pre_start[&#39;exposure_days&#39;].apply(lambda x: x.days) is there a way to get the number of days, circumventing this error?

答案1

得分: 1

你应该使用dt访问器:

pre_start['exposure_days'] = (datetime.now() - pd.to_datetime(pre_start['First_Receive_Date'])).dt.days
英文:

What you should do is use the dt accessor:

pre_start[&#39;exposure_days&#39;] = (datetime.now() - pd.to_datetime(pre_start[&#39;First_Receive_Date&#39;])).dt.days

huangapple
  • 本文由 发表于 2023年4月11日 06:50:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定