Skip to content Skip to sidebar Skip to footer

How To Compare Two Date By Iterating In A Pandas Data Frame And Create A New Column

I have a pandas data frame with customer transactions as shown below and create a column named 'Label' with 2 different values New Transaction performed before the end date of the

Solution 1:

Use numpy.where and Series.shift:

import numpy as np

df['Label'] = np.where(df['Transaction Start Date'].lt(df['Transaction End Date'].shift()), 'New Transaction performed before end date of previous transaction', 'New Transaction after the end date of previous transaction.')

Solution 2:

Use to_datetime first, then numpy.where with Series.lt form less compred shifted values by Series.shift and last set first value to empty string:

df['Transaction End Date'] = pd.to_datetime(df['Transaction End Date'])
df['Transaction Start Date'] = pd.to_datetime(df['Transaction Start Date'])

df['Label'] = np.where(df['Transaction Start Date'].lt(df['Transaction End Date'].shift()), 
                       'New Transaction performed before end date of previous transaction', 
                       'New Transaction after the end date of previous transaction.')
df.loc[0, 'Label'] = ''

Alternative solution:

m = df['Transaction Start Date'].lt(df['Transaction End Date'].shift())

df['Label'] = [''] + np.where(m, 
              'New Transaction performed before end date of previous transaction', 
              'New Transaction after the end date of previous transaction.')[1:].tolist()

print (df)
   Transaction ID Transaction StartDate Transaction EndDate  \
012014-06-232014-07-15122014-07-142014-08-08232014-08-132014-08-22342014-08-212014-08-28452014-08-292014-09-05562014-09-062014-09-15   

                                               Label  
                                                     
1New Transaction performed before enddateof p...  
2New Transaction after the enddateof previous...  
3New Transaction performed before enddateof p...  
4New Transaction after the enddateof previous...  
5New Transaction after the enddateof previous...  

Post a Comment for "How To Compare Two Date By Iterating In A Pandas Data Frame And Create A New Column"