Pandas - 将派生日期时间转换为整数

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

Pandas - Converting Derived Datetime to Integer

pythonpandas

提问by Jeff Saltfist

I have a pandas dataframe, 'df', where there is an original column with dates in datetime format. I set a hard date as a variable:

我有一个 Pandas 数据框“df”,其中有一个原始列,日期为日期时间格式。我将一个硬日期设置为变量:

 hard_date = datetime.date(2013, 5, 2)

I then created a new column in my df with the difference between the values in the date column and the hard_date...

然后我在我的 df 中创建了一个新列,其中 date 列中的值与 hard_date 中的值之间存在差异...

df['days_from'] = df['date'] - hard_date

This produced a good output. for instance, when I print the first cell in the new column it shows:

这产生了良好的输出。例如,当我打印新列中的第一个单元格时,它显示:

print (df['days_from'].iloc[0])

28 days 00:00:00

But now I want to convert the new column to just the number of days as an integer. I thought about just taking the first 2 characters, but many of the values are negative, so I am seeking a better route.

但现在我想将新列转换为整数天数。我想只取前2个字符,但许多值都是负数,所以我正在寻找更好的路线。

Any thoughts on an efficient way to convert the column to just the integer of the days?

关于将列转换为天数的有效方法的任何想法?

Thanks

谢谢

回答by miradulo

Just use the .dtaccessor and .daysattribute on the timedeltas.

只需在 timedeltas 上使用.dt访问器和.days属性。

df.days_from = df.days_from.dt.days