【问题标题】:How to extract two integer values from a column of a dataframe如何从数据框的列中提取两个整数值
【发布时间】:2019-12-03 23:40:19
【问题描述】:

我有一个名为 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()]

【问题讨论】:

    标签: python pandas dataframe digits


    【解决方案1】:

    这应该可以满足您的需求:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 2019-04-10
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多