In[2]: df=pd.DataFrame([1,15], [2,30], [3,0]], columns=['hour', 'minute'])
: df
Out [2]:
hour minute
0 1 15
1 2 30
2 3 0
If you are given a data frame like the one above, and you only want to do it with dataframe's own string operation,
In[3]:df[[['hour', 'minute']].astype(str).apply(lambdas:s.str.zfill(2)).apply(
: lambdas: s.str.cat(sep=':'),
: axis = 1
: )
Out [3]:
0 01:15
1 02:30
2 03:00
dtype:object
I thought it would be.
I got an error because both hour and minute are int type and it doesn't work.
Then maybe you should convert it to a string type
import pandas as pd
df = pd.DataFrame({'hour': [1,2,3], 'minute': [10,20,30]})
r=df.hour.astype(str)+":"+df.minute.astype(str)
#0 1:10
#1 2:20
#2 3:30
# dtype:object
If you use apply, it looks like this
r=df [['hour', 'minute']].astype(str).apply(':'.join,axis=1)
#0 1:10
#1 2:20
#2 3:30
# dtype:object
The second method can be done without a string type
r=df.apply(lambdad:f"{d.hour}:{d.minute:02d}",axis=1)
#0 1:10
#1 2:20
#2 3:30
# dtype:object
Is this the simplest?
© 2025 OneMinuteCode. All rights reserved.