日期之间的差异np数组 - 当前日期

问题描述 投票:2回答:3

我试图找到Pandas Dataframe中的日期列表与当前日期之间的天数。

我想创建一个新列,其中包含截止日期和当前日期之间的天数。例如:

+---------------------+------------+
|      Due Date       | Difference |
+---------------------+------------+
| 2019-04-15 00:00:00 |        146 |
| 2019-02-11 00:00:00 |         83 |
| 2019-03-11 00:00:00 |        111 |
| 2019-01-04 00:00:00 |         45 |
| 2019-05-13 00:00:00 |        174 |
+---------------------+------------+

我试图这样做:

current = np.datetime64('today')
df['Difference'] = df['Due Date'] - current

但我得错了数字。如果我单独做它们,它可以正常工作:

df['Due Date'][0] - current

任何帮助都会很棒。谢谢!

python pandas numpy datetime
3个回答
1
投票

但我得错了数字。

假设Due Datedatetime系列,在Pandas 0.23 / NumPy 1.14.3上对我工作正常:

print(df['Due Date'] - np.datetime64('today'))

0   146 days
1    83 days
2   111 days
3    45 days
4   174 days
Name: Due Date, dtype: timedelta64[ns]

如果你想要整数,更惯用的是使用Pandas生成的对象和dt.days

print((df['Due Date'] - pd.Timestamp('today')).dt.days)

0    145
1     82
2    110
3     44
4    173
Name: Due Date, dtype: int64

请注意,例如,使用NumPy版本导致的一天差异。真正的答案是在两者之间,但是四舍五入可能不是人们所期望的。


2
投票

我认为你需要将它们转换为datetime来执行类似日期的操作。

df['Due Date'] = pd.to_datetime(df['Due Date'])

所以完整的代码看起来像这样:

df['Due Date'] = pd.to_datetime(df['Due Date'])
current = np.datetime64('today')
df['Difference'] = df['Due Date'] - current

编辑:另一个可能的问题:我认为你需要将当前日期添加为列(或熊猫系列),所以一个很好的解决方案将是:

current = np.datetime64('today')
df['current'] = np.datetime64('today')
df['Difference'] = df['Due Date'] - df['current']

0
投票

我会检查df["Due Date"]的格式。如果它与今天的日期格式不同,则切换它。如果格式匹配,广播(简单减法)应该有效。

否则,请尝试使用lambda函数来应用更改:

df['Difference'] = df['Due Date'].apply(lambda x: x - current, axis=1)

© www.soinside.com 2019 - 2024. All rights reserved.