Python:在数据帧中将 timedelta 转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25646200/
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-18 23:25:36  来源:igfitidea点击:

Python: Convert timedelta to int in a dataframe

pythonpandastimedelta

提问by Asaf Hanish

I would like to create a column in a pandas data frame that is an integer representation of the number of days in a timedelta column. Is it possible to use 'datetime.days' or do I need to do something more manual?

我想在 Pandas 数据框中创建一列,它是 timedelta 列中天数的整数表示。是否可以使用“datetime.days”或者我需要做一些更手动的事情吗?

timedelta column

时间增量列

7 days, 23:29:00

7 天,23:29:00

day integer column

日整数列

7

7

回答by chrisb

You could do this, where tdis your series of timedeltas. The division converts the nanosecond deltas into day deltas, and the conversion to int drops to whole days.

你可以这样做,td你的时间增量系列在哪里。除法将纳秒增量转换为天增量,转换为 int 下降到整天。

import numpy as np

(td / np.timedelta64(1, 'D')).astype(int)

回答by abeboparebop

Use the dt.daysattribute. Access this attribute via:

使用dt.days属性。通过以下方式访问此属性:

timedelta_series.dt.days

You can also get the secondsand microsecondsattributes in the same way.

您也可以用同样的方式获取secondsmicroseconds属性。

回答by Qiao Zhang

Timedelta objects have read-only instance attributes .days, .seconds, and .microseconds.

Timedelta对象具有只读实例属性.days.seconds.microseconds

回答by CheapSquier

If the question isn't just "how to access an integer form of the timedelta?" but "how to convert the timedelta column in the dataframe to an int?" the answer might be a little different. In addition to the .dt.daysaccessor you need either df.astypeor pd.to_numeric

如果问题不仅仅是“如何访问 timedelta 的整数形式?” 但是“如何将数据帧中的 timedelta 列转换为 int?” 答案可能略有不同。除了访问.dt.days器之外,您还需要df.astypepd.to_numeric

Either of these options should help:

这些选项中的任何一个都应该有帮助:

df['tdColumn'] = pd.to_numeric(df['tdColumn'].dt.days, downcast='integer')

or

或者

df['tdColumn'] = df['tdColumn'].dt.days.astype('int16')