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

为何无法对Pandas DataFrame执行unstack操作?

Pandas unstack报错:Index contains duplicate entries, cannot reshape 原因排查与解决

问题场景

尝试对Pandas DataFrame的variable层级执行unstack操作时,持续触发错误:

ValueError: Index contains duplicate entries, cannot reshape

原始DataFrame结构如下(多级索引包含variable, n_channel, n_pulse, n_x层级,列对应n_y):

n_y                                                       0         1         2         3         4   ...        53        54        55        56        57
variable                     n_channel n_pulse n_x                                                    ...                                                   
Total collected charge (V s) 1         1       0    0.000021  0.000039  0.000028  0.000029  0.000030  ...  0.000099  0.000085  0.000031  0.000017  0.000035
                                               1    0.000028  0.000133  0.000046  0.000049  0.000063  ...  0.000237  0.000165  0.000037  0.000036  0.000067
                                               2    0.000022  0.000027  0.000054  0.000075  0.000023  ...  0.000105  0.000045  0.000122  0.000044  0.000022
                                               3    0.000042  0.000171  0.000016  0.000027  0.000046  ...  0.000030  0.000054  0.000055  0.000103  0.000044
                                               4    0.000031  0.000020  0.000043  0.000017  0.000028  ...  0.000024  0.000033  0.000040  0.000069  0.000034
...                                                      ...       ...       ...       ...       ...  ...       ...       ...       ...       ...       ...
                             4         2       53   0.000491  0.000047  0.000014  0.000025  0.000027  ...  0.000048  0.000029  0.000089  0.000051  0.000026
                                               54   0.000022  0.000081  0.000069  0.000050  0.000038  ...  0.000040  0.000077  0.000039  0.000033  0.000017
                                               55   0.000081  0.000091  0.000015  0.000072  0.000016  ...  0.000042  0.000046  0.000024  0.000087  0.000026
                                               56   0.000031  0.000049  0.000273  0.000022  0.000122  ...  0.000028  0.000020  0.000033  0.000053  0.000022
                                               57   0.000027  0.000018  0.000069  0.000012  0.000048  ...  0.000117  0.000031  0.000084  0.000019  0.000018

[2320 rows x 58 columns]

但自行编写的最小可复现示例(MWE)可以正常执行unstack('variable')并得到预期结果:

import pandas
import numpy

df = []
stuff = []
for variable in ['amplitude','time']:
    for n_channel in ['CH1','CH2','CH3']:
        for n_x in range(9):
            for n_y in range(9):
                for n_pulse in [1,2]:
                    stuff.append(
                        dict(
                            variable = variable,
                            n_channel = n_channel,
                            n_x = n_x,
                            n_y = n_y,
                            whatever = numpy.random.rand(),
                            n_pulse = n_pulse,
                        )
                    )
df = pandas.DataFrame.from_records(stuff)
df = pandas.pivot_table(
    data = df,
    values = df.columns,
    index = ['variable','n_channel','n_pulse','n_x'],
    columns = 'n_y',
)
df = df['whatever']
print(df)
df = df.unstack('variable')
print(df)

核心原因

unstack操作的核心要求是:除了要被unstack的层级外,剩余的索引组合必须唯一。

你的MWE中,variable, n_channel, n_pulse, n_x的每一组组合都是唯一的(循环生成时无重复),因此unstack可以正常执行;但原始DataFrame的多级索引中,存在重复的(n_channel, n_pulse, n_x)组合对应同一个variable的情况,导致Pandas无法确定如何将重复条目重塑为列结构。

验证重复索引的方法

可以通过以下代码检查原始DataFrame的索引是否存在重复:

# 找出所有重复的索引条目
duplicate_indices = df.index.duplicated(keep=False)
# 查看重复的行
print(df[duplicate_indices])

# 或者统计每个索引组合出现的次数
print(df.index.value_counts().sort_values(ascending=False))

解决办法

  1. 合并重复条目:如果重复是数据冗余导致的,可以通过聚合操作合并重复项,比如取均值、求和或保留第一条:
# 按索引分组,取均值合并
df = df.groupby(df.index).mean()
# 或者保留第一条
df = df.groupby(df.index).first()
  1. 修复数据来源:检查原始数据的生成或导入流程,找到重复索引产生的原因(比如重复写入、数据拼接错误等),从源头避免重复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:39:51