Search code examples
pythonpandastimestring-concatenation

Elegant way to concatenate string in one column to several columns in df


I have a df structured as so:

   CUID    DATE        T1         T2         T3
0  1000   5/5/2016   3:58:54    4:02:00    4:15:05
1  1001   5/6/2016  17:23:39   17:24:00   17:44:32
2  1002   5/7/2016  18:20:50   18:22:00   18:37:34
3  1003   5/7/2016  21:30:29   21:35:00   21:45:51
4  1004   5/9/2016  22:33:19   22:34:00   22:41:54
...

I want to take the date (string) and concatenate to each time string (i.e., T1, T2, T3). In other words, i want it to look like this:

  CUID    DATE             T1                  T2                 T3
0  1000   5/5/2016  5/5/2016 3:58:54    5/5/2016 4:02:00   5/5/2016 4:15:05
1  1001   5/6/2016  5/5/2016 17:23:39   5/5/2016 17:24:00  5/5/2016 17:44:32
2  1002   5/7/2016  5/5/2016 18:20:50   5/5/2016 18:22:00  5/5/2016 18:37:34
3  1003   5/7/2016  5/5/2016 21:30:29   5/5/2016 21:35:00  5/5/2016 21:45:51
4  1004   5/9/2016  5/5/2016 22:33:19   5/5/2016 22:34:00  5/5/2016 22:41:54
...

I know I can do this using the following code:

df['T1'] = pd.to_datetime(df.DATE.str.cat(' ' + df['T1']))
df['T2'] = pd.to_datetime(df.DATE.str.cat(' ' + df['T2']))
df['T3'] = pd.to_datetime(df.DATE.str.cat(' ' + df['T3']))

But I was wondering if there was a more elegant/efficient way?


Solution

  • You can call apply and in the lambda just add the DATE column with a space and the column of interest.

    Here apply will iterate over the sub-selected columns:

    In[8]:
    df.loc[:,'T1':] = df.loc[:,'T1':].apply(lambda x: df['DATE'] + ' ' + x)
    df
    
    Out[8]:
    CUID      DATE                 T1                 T2                 T3
    0  1000  5/5/2016   5/5/2016 3:58:54   5/5/2016 4:02:00   5/5/2016 4:15:05
    1  1001  5/6/2016  5/6/2016 17:23:39  5/6/2016 17:24:00  5/6/2016 17:44:32
    2  1002  5/7/2016  5/7/2016 18:20:50  5/7/2016 18:22:00  5/7/2016 18:37:34
    3  1003  5/7/2016  5/7/2016 21:30:29  5/7/2016 21:35:00  5/7/2016 21:45:51
    4  1004  5/9/2016  5/9/2016 22:33:19  5/9/2016 22:34:00  5/9/2016 22:41:54