Reputation: 763
I've read many topics here and tried many different things but it did not work somehow. Basically, I have a field called order_date which was "object" initially. I've converted it to datetime64[ns] by applying this function :
customer_data['order_date'] = pd.to_datetime(customer_data['order_date'])
Now, I'd like to calculate the difference between two timedeltas and get an integer value like this :
customer_data['recency']= (customer_data.order_date.max() - customer_data['order_date'])
But when I do this, I want my new column "recency" to be an INTEGER value rather than a timedelta64[ns] . Any idea how to do this?
Many thanks in advance.
Upvotes: 1
Views: 79
Reputation: 862511
I think you can use dt.total_seconds
with casting to int
by astype
:
customer_data['recency'] = customer_data['recency'].dt.total_seconds().astype(int)
Sample:
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
Another solution with 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
Upvotes: 1