如何在Pandas中将天转换为小时

j8yoct9x  于 2023-01-07  发布在  其他
关注(0)|答案(4)|浏览(334)

示例:

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

o/p:

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

如何在Pandas中将天转换为小时

pxiryf3j

pxiryf3j1#

您可以使用pd.to_timedelta,但expiration列中的值必须是有效的timedelta字符串:

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
41ik7eoe

41ik7eoe2#

您可以在expiration列上使用str.replace,并使用regex模式来选择那些带有day(d)后缀的条目,还可以调用repl参数的函数-我选择在该参数中转换为hours。

代码:

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)

输出:

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

正则表达式模式:

r'^\d+d$'
  • ^:字符串的开始
  • \d+:一位或多位数字[0 - 9]
  • d:后跟字母d
  • $:字符串结束

注:

如果你更喜欢使用lambda函数的一行程序

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)
wvmv3b1j

wvmv3b1j3#

简单的Apply可以帮助您

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
2lpgd968

2lpgd9684#

基于eval的另一种可能的解决方案是:

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

输出:

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

相关问题