Home > database >  How to convert days to hours in pandas
How to convert days to hours in pandas

Time:01-04

Example:

coupon             expiration
Restaurant         1d
College            2d
Coffee House       2h

o/p:

coupon             expiration
Restaurant         24h
College            48h
Coffee House       2h

How to convert days to hours in pandas

CodePudding user response:

You can use pd.to_timedelta, but the values in the expiration column must be valid timedelta strings:

import pandas as pd

df = pd.read_clipboard() # Your df here

tds = pd.to_timedelta(df["expiration"])
# 0   1 days 00:00:00
# 1   2 days 00:00:00
# 2   0 days 02:00:00
# Name: expiration, dtype: timedelta64[ns]

# I would recommend stopping here, but you can reformat this into a string of hours:
df["expiration"] = tds.dt.total_seconds().div(3600).apply("{:g}h".format)

#         coupon expiration
# 0   Restaurant        24h
# 1      College        48h
# 2  CoffeeHouse         2h

CodePudding user response:

You can use str.replace on the expiration column and use a regex pattern to select those entries that have a day (d) suffix. You can also call a function for the repl parameter - which is where I chose to do the conversion to hours.

Code:

import pandas as pd

df = pd.DataFrame({"coupon":['Restaurant','College','Coffee House'], "expiration":['1d','2d','2h']})

def replacement(m):
    x = int(m.group(0).split('d')[0]) * 24
    return f"{x}h"

df.expiration = df.expiration.str.replace(pat=r'^\d d$', repl=replacement, regex=True)
print(df)

Output:

         coupon expiration
0    Restaurant        24h
1       College        48h
2  Coffee House         2h


Regex Pattern:

r'^\d d$'
  • ^ : start of string
  • \d : one or more digits [0-9]
  • d : followed by the letter d
  • $ : end of string

Note:

If you would rather a one-liner using a lambda function instead:

df.expiration = df.expiration.str.replace(pat=r'^\d d$', repl= lambda m:f"{int(m.group(0).split('d')[0]) * 24}h", regex=True)

CodePudding user response:

A simply Apply can help here

def convert(x):
    if 'd' in x:
        return f"{int(x.replace('d',''))*24}h"
    return x   
df['expiration']= df['expiration'].apply(lambda x:convert(x))
df
Out[57]: 
         coupon expiration
0    Restaurant        24h
1       College        48h
2  Coffee House         2h

CodePudding user response:

Another possible solution, based on eval:

df['expiration'] = [str(eval(x))   'h' for x in
                    df['expiration'].str.replace('d', '*24').str.replace('h', '')]

Output:

         coupon expiration
0    Restaurant        24h
1       College        48h
2  Coffee House         2h
  • Related