DIFFERENCE |
---|
3:52 |
0:04 |
2:58 |
1:21 |
2:25 |
I have a column that has time difference in hh:mm
format.
I need a new column that says: If it is 3:52, I want the new column to have 3 hours 52 minutes as the output. I want to apply that to the whole column in the dataframe.
Thank you.
CodePudding user response:
I'm assuming your column is that of a pandas dataframe.
import datetime as dt
def format_hhmm(value: str) -> str:
as_datetime = dt.datetime.strptime(value, "%H:%M")
return f"{as_datetime.hour} hours {as_datetime.minute} minutes"
df['difference_human_readable'] = df['DIFFERENCE'].apply(format_hhmm)
This will create a new column called "difference_human_readable" that row wise applies the string formatting function "format_hmm". This assumes your values are string.
CodePudding user response:
import pandas as pd
def convert_time(value):
time = value.split(':')
return f'{time[0]} hours {time[1]} minutes'
df = pd.DataFrame({'Difference': ['3:52', '0:04', '2:58', '1:21', '2:25']})
df['Diff_str'] = df['Difference'].apply(convert_time)
print(df)
CodePudding user response:
There are many possibile solutions. One of them is to .apply() a transformation function:
import pandas as pd
df=pd.DataFrame({"DIFFERENCE": [
"3:52",
"0:04",
"2:58",
"1:21",
"2:25"
]})
def conversion(date):
return date.split(":")[0] " hours " date.split(":")[1] " minutes"
df["DIFFERENCE_2"] = df["DIFFERENCE"].apply(conversion)
print(df)