gpt4 book ai didi

python - 如何从数据帧的列中提取两个整数值

转载 作者:行者123 更新时间:2023-12-01 13:12:21 25 4
gpt4 key购买 nike

我有一个名为 StaffHours_df 的数据框,看起来类似于以下内容:


Name Hours Description

Maria 5 hours 10 minutes Volunteer

Taylor 2 hours 4 minutes Employee

Ben 4hrs 30mins Employee

Gary 8 hours 40 mins Volunteer

我想提取小时数和分钟数来创建一个所有员工的总工作时间数字,但仅限于被归类为“员工”而不是志愿者的人。 我希望这个数字作为数据框的一个单独值进行总计 - 例如上表应该给出:timeWorked = [6, 34] 或 minutesWorked = 394 或类似的我必须考虑员工输入时间格式的差异,但我认为如果我使用 .isdigit,这不会成为问题。

虽然我正在寻找代码,但这是我所得到的:

StaffHours_df[StaffHours_df['Description'].str.containts['Employee']

s= [int(s) for s in str.split() if s.isdigit()]

最佳答案

这应该给你你所需要的:

df_emp = df[df['Description'] == 'Employee'] # filter for employees
df_emp['total_minutes'] = (df_emp['Hours']
.map(lambda x: [int(i) for i in re.findall("[0-9]+", x)]) # get list of intergers
.map(lambda x: 60 * x[0] + x[1]) # convert to minutes
)
print(df_emp.to_string())

Name Hours Description total_minutes
1 Taylor 2 hours 4 minutes Employee 124
2 Ben 4hrs 30mins Employee 270

关于python - 如何从数据帧的列中提取两个整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59166999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com