Python: Convert timedelta to int in a dataframe

浪尽此生 提交于 2019-11-26 05:20:06

问题


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?

timedelta column

7 days, 23:29:00

day integer column

7


回答1:


Use the dt.days attribute. Supposing td is the name of your timedelta Series, access this attribute via:

td.dt.days

You can also get the seconds and microseconds attributes in the same way.




回答2:


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

import numpy as np

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



回答3:


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




回答4:


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.days accessor you need either df.astype or pd.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')


来源:https://stackoverflow.com/questions/25646200/python-convert-timedelta-to-int-in-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!