Reputation: 13660
I have a pandas dataframe.
Data = pd.DataFrame([[datetime.datetime(2014,1,1),datetime.datetime(2014,1,3)]],columns=['date1','date2')
That dataframe has two datetime columns date1 and date2.
I want to create a new column that contains a string in the format below:
'1/1/2014 - 1/3/2014'
Right now I have this setup to create the new column, but it keeps the trailing hms:
Data['range'] = Data.apply(lambda x:'%s - %s' % (x['date1'],x['date2']),axis=1)
Finding it hard to strip just the date out since I am working with two columns rather than two values. Any pointers?
Upvotes: 2
Views: 1745
Reputation: 238229
I think this should help:
import pandas as pd
from datetime import datetime
Data = pd.DataFrame([[datetime(2014,1,1),
datetime(2014,1,3)]],
columns=['date1','date2'])
#
Data['range'] = Data.apply(lambda x:'%s - %s' %
(x['date1'].to_pydatetime().strftime("%d/%m/%Y"),
x['date2'].to_pydatetime().strftime("%d/%m/%y")),
axis=1)
print(Data)
Result is:
date1 date2
0 2014-01-01 2014-01-03
date1 date2 range
0 2014-01-01 2014-01-03 01/01/2014 - 03/01/14
Upvotes: 1
Reputation: 64318
Finding it hard to strip just the date out since I am working with two columns rather than two values
Well, since you're already using apply
, you're dealing with two values (not columns), so you can call the date
method on each:
Data.apply(
lambda x: '%s - %s' % ( xdate1.date() , x.date2.date() ),
axis=1)
The x
passed to your lambda function is a single row of your dataframe, so accessing x.date1
(or x['date1']
) gives a single value of type Timestamp
. It's easy to extract just the date from that.
Upvotes: 1