How to display the time in the desired format

Asked 2 years ago, Updated 2 years ago, 44 views

I would like to create a time column ("%H:%M") from the data frame by pandas, with an hour column of 0-23 and a minute column of 0-60.
However, it doesn't work because both the hour and minute are int types.
What should I do?

python python3 pandas

2022-09-30 21:45

2 Answers

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.


2022-09-30 21:45

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?


2022-09-30 21:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.