将时间增量转换为 pandas 中的整数值

converting timedeltas to integer values in pandas

我在这里阅读了很多主题并尝试了很多不同的方法,但不知何故没有奏效。 基本上,我有一个名为 order_date 的字段,最初是 "object"。我已通过应用此函数将其转换为 datetime64[ns] :

customer_data['order_date'] = pd.to_datetime(customer_data['order_date'])

现在,我想计算两个 timedelta 之间的差异,并得到一个整数值,如下所示:

customer_data['recency']= (customer_data.order_date.max() - customer_data['order_date'])

但是当我这样做时,我希望我的新列 "recency" 是一个 INTEGER 值而不是 timedelta64[ns] 。知道怎么做吗?

非常感谢。

我想你可以使用 dt.total_seconds with casting to int by astype:

customer_data['recency'] = customer_data['recency'].dt.total_seconds().astype(int)

样本:

rng = pd.date_range('2017-04-03', periods=10)
customer_data = pd.DataFrame({'order_date': rng, 'a': range(10)})  
#print (customer_data)

customer_data['recency']= (customer_data.order_date.max() - customer_data['order_date'])
customer_data['recency'] = customer_data['recency'].dt.total_seconds().astype(int)
print (customer_data)
   a order_date  recency
0  0 2017-04-03   777600
1  1 2017-04-04   691200
2  2 2017-04-05   604800
3  3 2017-04-06   518400
4  4 2017-04-07   432000
5  5 2017-04-08   345600
6  6 2017-04-09   259200
7  7 2017-04-10   172800
8  8 2017-04-11    86400
9  9 2017-04-12        0

dt.days的另一个解决方案:

customer_data['recency'] = customer_data['recency'].dt.days.astype(int)
print (customer_data)
   a order_date  recency
0  0 2017-04-03        9
1  1 2017-04-04        8
2  2 2017-04-05        7
3  3 2017-04-06        6
4  4 2017-04-07        5
5  5 2017-04-08        4
6  6 2017-04-09        3
7  7 2017-04-10        2
8  8 2017-04-11        1
9  9 2017-04-12        0