python - 将具有不同名称的多列上的数据帧从宽格式转换为长格式

标签 python pandas dataframe pivot melt

我有一个形状为 500x200 的数据框,我想根据列的子集旋转/融化它。这是一个示例测试数据帧,其中有一个 id 列、三个 case 列以及一个包含每个 id 数据的附加列。

pd.DataFrame({'id': [1,2], 'case1': [3,1], 'case2': [3,2], 'case3': [3,2], 'vpd': [2,1]})

    id  case1 case2 case3 vpd
0   1   3     3     3     2
1   2   1     2     2     1

我只想以案例列为中心,如下所示:

pd.DataFrame({'index': ['case1', 'case2', 'case3', 'case1', 'case2', 'case3'], 'id': [1,1,1,2,2,2], 'vpd': [2,2,2,1,1,1],
             'case': [3,3,3,1,2,2]}).set_index('index')
        id vpd case
index           
case1   1   2   3
case2   1   2   3
case3   1   2   3
case1   2   1   1
case2   2   1   2
case3   2   1   2

每个案例列都成为透视数据框中的一行。这似乎达到了我想要的目的:

pd.wide_to_long(test_df, "case", i="id", j="case#").reset_index()
    id  case#   vpd case
0   1   1       2   3
1   2   1       1   1
2   1   2       2   3
3   2   2       1   2
4   1   3       2   3
5   2   3       1   2

但不完全是。关于如何达到我想要的输出还有其他想法吗?

最佳答案

您可以使用melt:

>>> (df.melt(['id', 'vpd'], var_name='case#', value_name='case', ignore_index=False)
       .set_index('case#'))

       id  vpd  case
case#               
case1   1    2     3
case1   2    1     1
case2   1    2     3
case2   2    1     2
case3   1    2     3
case3   2    1     2

要保持顺序,请使用堆栈:

>>> (df.set_index(['id', 'vpd']).stack()
       .rename('case').reset_index(['id', 'vpd']))

       id  vpd  case
case1   1    2     3
case2   1    2     3
case3   1    2     3
case1   2    1     1
case2   2    1     2
case3   2    1     2

关于python - 将具有不同名称的多列上的数据帧从宽格式转换为长格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75759146/

相关文章:

python - 在 OS X 上的 Python 上运行 32 位库和二进制文件

python - 当我调用其他类中的方法时,出现 AttributeError

python - Pandas:处理具有多种数据类型的列

python - 从数据框中的列表中重命名列中的值

python - 如何改进我的回归模型,使随机森林回归更准确

dataframe - 在 Julia Juno 中查看类似函数

python - Pandas - 如何将数据框中的日期范围分割为额外列

r - 如何根据 R 中列中的值组合排除行?

Python请求: Anyway to download just the body of a get response?

python - Apache:重定向到 WSGI 脚本错误?