【问题标题】:split pandas dataframe row into multiple rows by tasks按任务将熊猫数据框行拆分为多行
【发布时间】:2021-12-04 07:57:25
【问题描述】:

我有一个 pandas 数据框,想将包含多个任务的每一行拆分为一个新行。

The dataframe columns are:
start_t_i = start time of a task.
end_t_i = end time of a task.
weight_i = cost of a task.

例如,假设我有以下数据框 df1:

task_name start_t1 end_t1 weight_1 start_t_2 end_t2 weight_2.. start_t_k end_t_k weight_k
john 5 7 1 9 10 9
sally 3 4 1 8 11 7 19 21 1
tom 1 2 3

我想把它转换成下面的df2:

task_name start_t end_t weight
john 5 7 1
john 9 10 9
sally 3 4 1
sally 8 11 7
sally 19 21 1
tom 1 2 3

到目前为止,通过假设每个人最多只有两个任务,我设法将 df1 手动转换为 df2。 我的问题是,当每个人最多有 k 个任务时,我怎样才能从 df1 获得诸如 df2 之类的 df。

【问题讨论】:

    标签: python pandas dataframe data-analysis data-cleaning


    【解决方案1】:

    如果我们假设每个任务都有一个start_t, end_t and weight_t 列,那么我们可以使用:

    cols = list(df.columns[1:])
    task_col = df.columns[0]
    dfs = []
    for i in range(0, len(cols), 3):
        subset_cols = cols[i:i+3]
        rename_cols = {subset_cols[0]: 'start_t', subset_cols[1]:'end_t', subset_cols[2]:'weight'}
        dfs.append(df[[task_col] + subset_cols].rename(columns=rename_cols))
    
    transformed_df = pd.concat(dfs, ignore_index=True).sort_values(by='task_name').dropna(subset=['start_t', 'end_t', 'weight']).reset_index(drop=True)
    

    输出:

      task_name  start_t  end_t  weight
    0      john      5.0    7.0     1.0
    1      john      9.0   10.0     9.0
    2     sally      3.0    4.0     1.0
    3     sally      8.0   11.0     7.0
    4     sally     19.0   21.0     1.0
    5       tom      1.0    2.0     3.0
    

    【讨论】:

      【解决方案2】:

      你可以melt的列,提取有效的列名和pivot

      df = df.replace("", np.NaN).melt("task_name").dropna()
      df["variable"] = df["variable"].str.extract("(^[A-Za-z]+)_")
      
      print (df.assign(count=df.groupby(["task_name", "variable"]).cumcount())
               .pivot(["count", "task_name"], "variable", "value")
               .reset_index(0, drop=True).sort_index())
      
      variable    end  start  weight
      task_name                     
      john        7.0    5.0     1.0
      john       10.0    9.0     9.0
      sally       4.0    3.0     1.0
      sally      11.0    8.0     7.0
      sally      21.0   19.0     1.0
      tom         2.0    1.0     3.0
      

      【讨论】:

      • 谢谢,我是 pandas 的新手,对融化功能一无所知。
      猜你喜欢
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多