如何将 Pandas 中的列组转换为行?

cry*_*oar 4 python dataframe python-3.x pandas

假设我有一个 DataFrame,如下所示:

姓名 第一小时内的工作时间 第一小时浪费的时间 工作时间为第 2 小时 第 2 小时浪费时间
45 15 40 20
酒吧 35 25 55 5
巴兹 50 10 45 15

我希望在第一小时列和第二小时列上使用熔化,使其看起来像这样:

姓名 小时数 工作时间以 hr 为单位 时间浪费在hr上
1 45 15
2 40 20
酒吧 1 35 25
酒吧 2 55 5
巴兹 1 50 10
巴兹 2 45 15

我如何将“第一小时的工作时间”和“第一小时浪费的时间”分组在一起,以便我可以将它们融合到同一行中?

Sea*_*ean 5

您可以使用:

df1 = df.set_index('Name')
df1.columns = df1.columns.str.split('in', expand=True)

df2 = (df1.stack()
          .sort_index(axis=1, ascending=False)
          .rename_axis(index=['Name', 'Hour number'])
          .add_suffix('in the hr')
          .reset_index()
      )

df2['Hour number'] = df2['Hour number'].str.extract(r'(\d+)')
Run Code Online (Sandbox Code Playgroud)

结果:

print(df2)

  Name Hour number  Time worked in the hr  Time wasted in the hr
0  foo           1                     45                     15
1  foo           2                     40                     20
2  bar           1                     35                     25
3  bar           2                     55                      5
4  baz           1                     50                     10
5  baz           2                     45                     15
Run Code Online (Sandbox Code Playgroud)