Python 从 numpy.timedelta64 值中提取天数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18215317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:14:00  来源:igfitidea点击:

extracting days from a numpy.timedelta64 value

pythonnumpypandas

提问by user7289

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.

我正在使用 pandas/python 并且我有两个日期时间序列 s1 和 s2,它们是在包含日期/时间的 df 字段上使用“to_datetime”函数生成的。

When I subtract s1 from s2

当我从 s2 中减去 s1

s3 = s2 - s1

s3 = s2 - s1

I get a series, s3, of type

我得到一个系列,s3,类型

timedelta64[ns]

timedelta64[ns]

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:

我如何看待该系列的 1 个元素:

s3[10]

s3[10]

I get something like this:

我得到这样的东西:

numpy.timedelta64(2069211000000000,'ns')

numpy.timedelta64(2069211000000000,'ns')

How do I extract days from s3 and maybe keep them as integers(not so interested in hours/mins etc.)?

我如何从 s3 中提取天数并将它们保留为整数(对小时/分钟等不太感兴趣)?

Thanks in advance for any help.

在此先感谢您的帮助。

采纳答案by Viktor Kerkez

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.

您可以将其转换为具有一天精度的 timedelta。要提取天数的整数值,请将其除以一天的时间增量。

>>> 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 timedeltais just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D', 'ns', ...).

或者,如@PhillipCloud建议,只是days.astype(int)因为timedelta仅仅是一个64位整数,根据你所传递的第二个参数被解释以各种方式('D''ns',...)。

You can find more about it here.

您可以在此处找到更多相关信息。

回答by mgoldwasser

Suppose you have a timedelta series:

假设您有一个 timedelta 系列:

import pandas as pd
from datetime import datetime
z = pd.DataFrame({'a':[datetime.strptime('20150101', '%Y%m%d')],'b':[datetime.strptime('20140601', '%Y%m%d')]})

td_series = (z['a'] - z['b'])

One way to convert this timedelta column or series is to cast it to a Timedelta object (pandas 0.15.0+) and then extract the days from the object:

转换此 timedelta 列或系列的一种方法是将其转换为 Timedelta 对象(pandas 0.15.0+),然后从对象中提取天数:

td_series.astype(pd.Timedelta).apply(lambda l: l.days)

Another way is to cast the series as a timedelta64 in days, and then cast it as an int:

另一种方法是将系列转换为 timedelta64(以天为单位),然后将其转换为 int:

td_series.astype('timedelta64[D]').astype(int)

回答by Nickil Maveli

Use dt.daysto obtain the days attribute as integers.

用于dt.days以整数形式获取 days 属性。

For eg:

例如:

In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T'))

In [15]: s
Out[15]: 
0    1 days 00:00:00
1    3 days 02:00:00
2    5 days 04:00:00
3    7 days 06:00:00
4    9 days 08:00:00
5   11 days 10:00:00
dtype: timedelta64[ns]

In [16]: s.dt.days
Out[16]: 
0     1
1     3
2     5
3     7
4     9
5    11
dtype: int64

More generally - You can use the .componentsproperty to access a reduced form of timedelta.

更一般地 - 您可以使用该.components属性来访问timedelta.

In [17]: s.dt.components
Out[17]: 
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     1      0        0        0             0             0            0
1     3      2        0        0             0             0            0
2     5      4        0        0             0             0            0
3     7      6        0        0             0             0            0
4     9      8        0        0             0             0            0
5    11     10        0        0             0             0            0

Now, to get the hoursattribute:

现在,要获取hours属性:

In [23]: s.dt.components.hours
Out[23]: 
0     0
1     2
2     4
3     6
4     8
5    10
Name: hours, dtype: int64