繁体   English   中英

如何在python中将小时和分钟的字符串转换为分钟?

[英]How to convert a string of hours and minutes to minutes in python?

我的数据框df中有一列:

Time
2 hours 3 mins
5 hours 10 mins
1 hour 40 mins

我想在df'Minutes'中创建一个新列,将此列转换为分钟

Minutes
123
310
100

有没有python函数来做到这一点?

您需要通过to_datetime进行转换

s=pd.to_datetime(df.Time.replace({'hours':'hour'},regex=True),format='%H hour %M mins')
s.dt.hour*60+s.dt.minute
Out[406]: 
0    123
1    310
2    100
Name: Time, dtype: int64

或者我们使用带有numpy dot str.findall

np.dot(np.array(df.Time.str.findall('\d+').tolist()).astype(int),[60,1])
Out[420]: array([123, 310, 100])

有趣的pd.eval

df['Minutes'] = pd.eval(
    df['Time'].replace(['hours?', 'mins'], ['*60+', ''], regex=True))
df
              Time Minutes
0   2 hours 3 mins     123
1  5 hours 10 mins     310
2   1 hour 40 mins     100

想法是将replace转换为数学表达式,然后让pandas评估它:

expr = df['Time'].replace(['hours?', 'mins'], ['* 60 +', ''], regex=True)
expr

0    2 * 60 +  3 
1    5 * 60 + 10 
2    1 * 60 + 40 
Name: Time, dtype: object

pd.eval(expr)
# array([123, 310, 100], dtype=object)

str.extract和multiplication

((df['Time'].str.extract(r'(\d+) hour.*?(\d+) min').astype(int) * [60, 1])
            .sum(axis=1))

0    123
1    310
2    100
dtype: int64

写一个简单的正则表达式来提取数字,然后使用简单的算术转换为分钟。 您可以将模式缩短为

(df['Time'].str.extract(r'(\d+)\D*(\d+)').astype(int) * [60, 1]).sum(axis=1)

0    123
1    310
2    100
dtype: int64

按照@Quang Hoang的建议。

“有这样的python函数吗?” 直到你写一个......

def to_minutes(time_string):
    hours, _, minutes, _ = time_string.split(' ')
    return int(hours) * 60 + int(minutes)

结果应该类似于:

>>> to_minutes('2 hours 3 mins')
123

我相信你可以转换为timedelta并转换为timedelta64[m]

pd.to_timedelta(df.Time.str.replace('mins', 'm'), unit='m').astype('timedelta64[m]')

Out[786]:
0    123.0
1    310.0
2    100.0
Name: Time, dtype: float64

如果您喜欢lambda函数,您还可以使用:

df.Time.apply(lambda x: sum(np.array([ int(i) for i in re.match(r'(\d+) hour[s]? (\d+) min[s]?', x).groups()]) * [60, 1]))

假设时间列始终采用相同的格式(相同的空间量),您可以使用 -

def Mins(row):
    return int(row['Time'].split(' ')[0])*60 + int(row['Time'].split(' ')[2])

df.apply(Mins,axis=1)

我不认为有内置函数,但你可以构建一个,然后在pappas中使用.apply()。

它可能不是最短的答案,但它会让你了解如何使用Pandas的基本Python函数。 我认为这非常有帮助!

我建的功能:

import re

def calculate_number_of_minutes(hours_string):
    regex = '\d+( )\w+'
    // I build a regex which can find a sequence of digits and a single word


    result = re.finditer(regex, text, re.DOTALL)
    // I find such patterns in the given string

    minutes = 0
    for element in result:
        fragment = element.group()

        if 'hour' in fragment:
            minutes += int(re.search('\d+', fragment).group()) * 60
            // if there are 'hours', the associated number is multiplied by 60
            // and added to the count
        else:
            minutes += int(re.search('\d+', fragment).group())

    return minutes


text = '5 hours 10 mins'
print(calculate_number_of_minutes(text))

它的作用是在字符串中搜索数字,然后计算分钟数。

要将其应用于您的列,请尝试以下操作:

data.loc[;, 'Time'] = data['Time'].apply(lambda x: calculate_number_of_minutes(x))

希望它有用;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM