pandas :减去两个日期列,结果是一个整数

Pandas: Subtracting two date columns and the result being an integer( pandas :减去两个日期列,结果是一个整数)
本文介绍了 pandas :减去两个日期列,结果是一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在 Pandas 数据框中有两列是日期.

I have two columns in a Pandas data frame that are dates.

我希望从另一列中减去一列,结果是天数的差异作为整数.

I am looking to subtract one column from another and the result being the difference in numbers of days as an integer.

查看数据:

df_test.head(10)
Out[20]: 
  First_Date Second Date
0 2016-02-09  2015-11-19
1 2016-01-06  2015-11-30
2        NaT  2015-12-04
3 2016-01-06  2015-12-08
4        NaT  2015-12-09
5 2016-01-07  2015-12-11
6        NaT  2015-12-12
7        NaT  2015-12-14
8 2016-01-06  2015-12-14
9        NaT  2015-12-15

我已经成功创建了一个新列,不同之处:

I have created a new column successfully with the difference:

df_test['Difference'] = df_test['First_Date'].sub(df_test['Second Date'], axis=0)
df_test.head()         
Out[22]: 
  First_Date Second Date  Difference
0 2016-02-09  2015-11-19     82 days
1 2016-01-06  2015-11-30     37 days
2        NaT  2015-12-04         NaT
3 2016-01-06  2015-12-08     29 days
4        NaT  2015-12-09         NaT

但是我无法获得结果的数字版本:

However I am unable to get a numeric version of the result:

df_test['Difference'] = df_test[['Difference']].apply(pd.to_numeric)     

df_test.head()
Out[25]: 
  First_Date Second Date    Difference
0 2016-02-09  2015-11-19  7.084800e+15
1 2016-01-06  2015-11-30  3.196800e+15
2        NaT  2015-12-04           NaN
3 2016-01-06  2015-12-08  2.505600e+15
4        NaT  2015-12-09           NaN

推荐答案

怎么样:

df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date']).dt.days

如果没有缺失值(NaT),这将返回差异为 int,如果有,则返回 float.

This will return difference as int if there are no missing values(NaT) and float if there is.

Pandas 有关于 时间序列/日期功能 和 时间增量

Pandas have a rich documentation on Time series / date functionality and Time deltas

这篇关于 pandas :减去两个日期列,结果是一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

build conda package from local python package(从本地 python 包构建 conda 包)
How can I see all packages that depend on a certain package with PIP?(如何使用 PIP 查看依赖于某个包的所有包?)
How to organize multiple python files into a single module without it behaving like a package?(如何将多个 python 文件组织到一个模块中而不像一个包一样?)
Check if requirements are up to date(检查要求是否是最新的)
How to upload new versions of project to PyPI with twine?(如何使用 twine 将新版本的项目上传到 PyPI?)
Why #egg=foo when pip-installing from git repo(为什么从 git repo 进行 pip 安装时 #egg=foo)