You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何去除重复行并生成新列?Pandas数据重塑求助

问题描述

原始数据表格:

Miles  Side  Direction  Param1   Width  Height  Date
0.5    Left  Right      5        0.6    0.8     2023-01-04
0.5    Right Right      5        0.5    0.9     2023-01-04
1      Left  Left       4        0.3    0.3     2023-01-04
1      Right Left       4        0.5    0.5     2023-01-04

需求:将Miles、Direction、Param1、Date作为唯一标识列,把每个分组内变化的Side、Width、Height字段转为横向新列(如Side1、Width1等),最终目标格式:

Miles   Direction   Param1  Side1   Width1  Height1 Side2   Width2  Height2 Date
0.5     Right       5       Left    0.6     0.8     Right   0.5     0.9  2023-01-04
1       Left        4       Left    0.3     0.3     Right   0.5     0.5  2023-01-04

尝试方法存在的问题:

  • 使用pivot函数时,因未区分分组内的多行,无法生成目标格式
  • 使用pivot_table的代码存在语法错误(index参数列名被写为带逗号的单个字符串,而非独立列表元素),导致结果完全错误:
df = pd.pivot_table(df, values=['Side','Width','Height'], index=['Miles, Direction','Param1','Date'], columns=None)
解决方案

正确思路是先给每个分组内的行添加序号后缀,再通过pivot实现列转行:

步骤1:加载数据并添加分组内序号

import pandas as pd

# 加载原始数据
data = [
    [0.5, 'Left', 'Right', 5, 0.6, 0.8, '2023-01-04'],
    [0.5, 'Right', 'Right', 5, 0.5, 0.9, '2023-01-04'],
    [1, 'Left', 'Left', 4, 0.3, 0.3, '2023-01-04'],
    [1, 'Right', 'Left', 4, 0.5, 0.5, '2023-01-04']
]
df = pd.DataFrame(data, columns=['Miles', 'Side', 'Direction', 'Param1', 'Width', 'Height', 'Date'])

# 给每个分组内的行添加序号(从1开始)
df['idx'] = df.groupby(['Miles', 'Direction', 'Param1', 'Date']).cumcount() + 1

步骤2:执行pivot并整理列名

# 执行pivot,用idx作为列的后缀
pivoted = df.pivot(
    index=['Miles', 'Direction', 'Param1', 'Date'],
    columns='idx',
    values=['Side', 'Width', 'Height']
)

# 合并列名,生成Side1、Width1这类格式
pivoted.columns = [f'{col[0]}{col[1]}' for col in pivoted.columns]

# 重置索引,将分组列转为普通列
result = pivoted.reset_index()

# 调整列顺序,匹配目标格式
result = result[['Miles', 'Direction', 'Param1', 'Side1', 'Width1', 'Height1', 'Side2', 'Width2', 'Height2', 'Date']]

最终输出结果

Miles Direction  Param1 Side1  Width1  Height1 Side2  Width2  Height2        Date
0    0.5     Right       5  Left     0.6      0.8  Right     0.5      0.9  2023-01-04
1    1.0      Left       4  Left     0.3      0.3  Right     0.5      0.5  2023-01-04

错误原因说明

你之前的pivot_table代码有两处关键问题:

  1. index参数格式错误,应传入独立列名列表['Miles', 'Direction', 'Param1', 'Date'],而非带逗号的单个字符串
  2. 未指定columns参数区分分组内的不同行,无法实现多行转横向列的需求

内容的提问来源于stack exchange,提问作者verynovice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:40:18