Psychefelic
Psychefelic

Reputation: 51

Concatenate Decimal Seconds in to a Time Column in Pandas

I have a column with hh:mm:ss and a separate column with the decimal seconds.

I have quite a horrible text files to process and the decimal value of my time is separated into another column. Now I'd like to concatenate them back in.

For example:

df = {'Time':['01:00:00','01:00:00 AM','01:00:01 AM','01:00:01 AM'], 
      'DecimalSecond':['14','178','158','75']} 

I tried the following but it didn't work. It gives me "01:00:00 AM.14" LOL

df = df['Time2'] = df['Time'].map(str) + '.' + df['DecimalSecond'].map(str) 

The goal is to come up with one column named "Time2" which has the first row 01:00:00.14 AM, second row 01.00.00.178 AM, etc)

Thank you for the help.

Upvotes: 1

Views: 130

Answers (2)

Vaitybharati
Vaitybharati

Reputation: 11

Please see the python code below

In [1]:
import pandas as pd
In [2]:
df = pd.DataFrame({'Time':['01:00:00','01:00:00','01:00:01','01:00:01'], 
                   'DecimalSecond':['14','178','158','75']})
In [3]:
df['Time2'] = df[['Time','DecimalSecond']].apply(lambda x: ' '.join(x), axis = 1)
print(df)
       Time DecimalSecond         Time2
0  01:00:00            14   01:00:00 14
1  01:00:00           178  01:00:00 178
2  01:00:01           158  01:00:01 158
3  01:00:01            75   01:00:01 75
In [4]:
df.iloc[:,2]
Out[4]:
0     01:00:00 14
1    01:00:00 178
2    01:00:01 158
3     01:00:01 75
Name: Time2, dtype: object

Upvotes: 0

jezrael
jezrael

Reputation: 863196

You can convert ouput to datetimes and then call Series.dt.time:

#Time column is splitted by space and extracted values before first space
s = df['Time'].astype(str).str.split().str[0] + '.' + df['DecimalSecond'].astype(str)
df['Time2'] = pd.to_datetime(s).dt.time
print (df)
         Time DecimalSecond            Time2
0     01:00:00            14  01:00:00.140000
1  01:00:00 AM           178  01:00:00.178000
2  01:00:01 AM           158  01:00:01.158000
3  01:00:01 AM            75  01:00:01.750000

Upvotes: 1

Related Questions