问题描述
我正在使用 pandas/python 并且我有两个日期时间序列 s1 和 s2,它们是在包含日期/时间的 df 字段上使用to_datetime"函数生成的.
当我从 s2 中减去 s1
s3 = s2 - s1
我得到一个系列 s3,类型为
timedelta64[ns]
0 385 天,04:10:361 57 天,22:54:002 642 天,21:15:233 615 天,00:55:444 160 天,22:13:355 196 天,23:06:496 23 天,22:57:177 2 天,22:17:318 622 天,01:29:259 79 天,20:15:1410 23 天,22:46:5111 268 天,19:23:0412 钠盐13 纳特14 583 天,03:40:39
我如何看待系列的 1 个元素:
s3[10]
我得到了这样的东西:
numpy.timedelta64(2069211000000000,'ns')
如何从 s3 中提取天数并将它们保留为整数(对小时/分钟等不太感兴趣)?
在此先感谢您的帮助.
您可以将其转换为具有日期精度的 timedelta.要提取天数的整数值,请将其除以一天的时间增量.
>>>x = np.timedelta64(2069211000000000, 'ns')>>>days = x.astype('timedelta64[D]')>>>天数/np.timedelta64(1, 'D')23或者,正如@PhillipCloud 建议的那样,只是 days.astype(int)
,因为 timedelta
只是一个 64 位整数,根据第二个参数以各种方式解释你传入 ('D'
, 'ns'
, ...).
您可以在此处找到更多相关信息.
I am using pandas/python and I have two date time series s1 and s2, that have been generated using the 'to_datetime' function on a field of the df containing dates/times.
When I subtract s1 from s2
I get a series, s3, of type
0 385 days, 04:10:36
1 57 days, 22:54:00
2 642 days, 21:15:23
3 615 days, 00:55:44
4 160 days, 22:13:35
5 196 days, 23:06:49
6 23 days, 22:57:17
7 2 days, 22:17:31
8 622 days, 01:29:25
9 79 days, 20:15:14
10 23 days, 22:46:51
11 268 days, 19:23:04
12 NaT
13 NaT
14 583 days, 03:40:39
How do I look at 1 element of the series:
I get something like this:
How do I extract days from s3 and maybe keep them as integers(not so interested in hours/mins etc.)?
Thanks in advance for any help.
You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.
>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23
Or, as @PhillipCloud suggested, just days.astype(int)
since the timedelta
is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D'
, 'ns'
, ...).
You can find more about it here.
这篇关于从 numpy.timedelta64 值中提取天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!