如何从Pandas的一系列字符串中提取小时和分钟

2024-09-24 02:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

这个看似简单的问题困扰了我好几个小时。我想将以下字符串转换为分钟。(如果可以的话,也可以是几小时几分钟)

foo['stringtime'] = pd.Series(['1 hour and 59 minutes','2 hours', np.nan, '38 minutes', '4 hours and 31 minutes'])

#What I've tried:
foo['stringtime'] = foo['stringtime'].str.replace(r'hours?','').str.replace(' minutes','').str.split(' and ')

然而,这将造成一种情况,即'2 hours''38 minutes'变成['2']['38']

#What I would like to happen:
foo.head()
output:
119
120
NaN (or 0)
38
271

有什么优美优雅的Python式方法可以做到这一点吗


Tags: and字符串foonpnanwhatreplaceseries
2条回答

尝试使用正则表达式

Ex:

import re

def p_time(val):
    try:
        t = 0
        h = re.search(r"(\d+) hour(s)?", val)
        if h:
            t += int(h.group(1)) * 60
        m = re.search(r"(\d+) minute(s)?", val)
        if m:
            t += int(m.group(1))
        return t
    except:
        pass
    return 0

s = pd.Series(['1 hour and 59 minutes','2 hours', np.nan, '38 minutes', '4 hours and 31 minute'])
print(s.apply(p_time).astype(int))

输出:

0    119
1    120
2      0
3     38
4    271
dtype: int32

另一种方法可能只是使用numexpr来计算数值方程:

import numexpr

foo = pd.Series(['1 hour and 59 minutes','2 hours', np.nan, '38 minutes', '4 hours and 31 minutes'])

(foo.str.replace(r' hours?','*60').str.replace(' minutes','').str.replace(' and ', '+')
    .fillna('0').apply(numexpr.evaluate))

输出:

0    119
1    120
2      0
3     38
4    271

相关问题 更多 >