python - 如何将 pandas 中的多列转换为单独的行/值?

标签 python pandas dataframe reshape

我确信这个问题已经得到解答,但不幸的是我不知道如何称呼这个操作,所以我的搜索失败了。它几乎就像一个反向数据透视表。

假设我有以下工资数据:

data = [
    {'employee': 1, 'date': '2020-01-04', 'reg': 8, 'ot': 0, 'dt': 0},
    {'employee': 1, 'date': '2020-01-05', 'reg': 4, 'ot': 4, 'dt': 0},
    {'employee': 1, 'date': '2020-01-06', 'reg': 0, 'ot': 0, 'dt': 4},
    {'employee': 2, 'date': '2020-01-04', 'reg': 6, 'ot': 2, 'dt': 0},
    {'employee': 2, 'date': '2020-01-05', 'reg': 3, 'ot': 5, 'dt': 0},
    {'employee': 2, 'date': '2020-01-06', 'reg': 0, 'ot': 4, 'dt': 0},
]

data_df = pd.DataFrame(data)

我需要做的是将每个员工/日期的每个费率(“reg”、“ot”和“dt”)分解为自己的行,其中有一列用于费率标签,一列用于小时数,保留其他非基于费率的列。此外,我不希望任何值为零的行。对于上面的数据,我希望得到:

result = [
    {'employee': 1, 'date': '2020-01-04', 'rate': 'reg', 'hours': 8},
    {'employee': 1, 'date': '2020-01-05', 'rate': 'reg', 'hours': 4},
    {'employee': 1, 'date': '2020-01-05', 'rate': 'ot', 'hours': 4},
    {'employee': 1, 'date': '2020-01-06', 'rate': 'dt', 'hours': 4},
    {'employee': 2, 'date': '2020-01-04', 'rate': 'reg', 'hours': 6},
    {'employee': 2, 'date': '2020-01-04', 'rate': 'ot', 'hours': 2},
    {'employee': 2, 'date': '2020-01-05', 'rate': 'reg', 'hours': 3},
    {'employee': 2, 'date': '2020-01-05', 'rate': 'ot', 'hours': 5},
    {'employee': 2, 'date': '2020-01-06', 'rate': 'ot', 'hours': 4},
]

result_df = pd.DataFrame(result)

任何关于如何实现这一目标的想法将不胜感激!

最佳答案

尝试使用melt :

(data_df.melt(['employee','date'], 
             var_name='rate', 
             value_name='hours')
        .query('hours != 0'))

输出:

    employee        date rate  hours
0          1  2020-01-04  reg      8
1          1  2020-01-05  reg      4
3          2  2020-01-04  reg      6
4          2  2020-01-05  reg      3
7          1  2020-01-05   ot      4
9          2  2020-01-04   ot      2
10         2  2020-01-05   ot      5
11         2  2020-01-06   ot      4
14         1  2020-01-06   dt      4

关于python - 如何将 pandas 中的多列转换为单独的行/值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59846232/

相关文章:

python - 使用 pandas.to_excel() 时没有 Excel 编写器 'openpyxl'

python - Pandas:根据与值对应的行数将列中的值替换为 'Other'

python - Pandas pd.DataFrame 转换为元组而不是 Dataframe

R根据具有添加条件的特定列合并两个数据集

python - 在 gtk3+ for python 中如何获取选定的菜单项或选定的菜单项的索引?

jquery - 使用 Django 和 jQuery 的订阅表单

python - 在python中增加财务季度

python - 按特定列对行(组内)的 Pandas df 子集进行排序

python - ROS Noetic (Ubuntu 20.04) - CV 桥不工作

python - 如何在 Pandas 列的分组条形图上添加误差线