出现以下代码错误:Traceback (most recent call last): File "D:\BaiduNetdiskWorkspace\PythonToTo\0000 其他用途命令\拼接多个execl表,保留表头.py", line 27, in <module> result = pd.concat(dataframes, axis=0, ignore_index=True) File "D:\BaiduNetdiskWorkspace\PythonToTo\venv\lib\site-packages\pandas\core\reshape\concat.py", line 385, in concat return op.get_result() File "D:\BaiduNetdiskWorkspace\PythonToTo\venv\lib\site-packages\pandas\core\reshape\concat.py", line 612, in get_result indexers[ax] = obj_labels.get_indexer(new_labels) File "D:\BaiduNetdiskWorkspace\PythonToTo\venv\lib\site-packages\pandas\core\indexes\base.py", line 3731, in get_indexer raise InvalidIndexError(self._requires_unique_msg) pandas.errors.InvalidIndexError: Reindexing only valid with uniquely valued Index objects 进程已结束,退出代码1
时间: 2023-06-30 14:10:11 浏览: 117
这个错误通常是由于拼接后的数据框中存在重复的行索引引起的。你可以尝试在拼接前将每个数据框的索引重置为唯一的整数索引,例如:
```python
import pandas as pd
import openpyxl
# 指定要拼接的表格文件名列表
filenames = [
'附件一:2022年12月末存量公司客户管户认领情况表__海沧-1.xlsx',
'附件三:2022年12月末存量机构客户管户认领情况表__海沧支行-1.xlsx',
'附件二:2023年3月末新拓公司客户管户认领情况表__海沧-1.xlsx',
'附件四:2023年3月末新拓机构客户管户认领情况表__海沧支行-1.xlsx'
]
# 使用 openpyxl 库的 load_workbook() 函数读取每个表格的数据,并将标题行单独读取出来
dataframes = []
headers = []
for filename in filenames:
wb = openpyxl.load_workbook(filename=filename, read_only=True, data_only=True)
ws = wb.worksheets[0]
df = []
for row in ws.iter_rows(values_only=True):
df.append(row)
df = pd.DataFrame(df[1:], columns=df[0])
header = pd.DataFrame(df.iloc[:1])
headers.append(header)
df = df.iloc[1:]
df.reset_index(drop=True, inplace=True) # 重置索引为唯一的整数索引
dataframes.append(df)
# 使用 Pandas 库的 concat() 函数将数据框拼接在一起
result = pd.concat(dataframes, axis=0, ignore_index=True)
# 将标题行合并为一个数据框,并使用 fillna() 函数将空值填充为前一个非空值
header = pd.concat(headers, axis=1, ignore_index=True)
header = header.fillna(method='ffill')
# 将标题行作为新数据框的列名
result.columns = header.iloc[0]
# 将拼接后的结果保存到新的 Excel 文件中
writer = pd.ExcelWriter('output.xlsx', engine='openpyxl')
result.to_excel(writer, index=False)
writer.save()
```
在这个例子中,我们使用 `reset_index` 函数将每个数据框的索引重置为唯一的整数索引,并在拼接前使用 `concat` 函数将它们拼接在一起。这样可以确保拼接后的数据框中不会存在重复的行索引。