pandas如何实现把一个excel中的多个sheet合并为一个sheet呢,具体思路如下:
1、读取excel获取每个的sheet的DataFrame对象,通过把read_excel的sheet_name参数设为None来实现。
2、设定一个空DataFrame对象用来拼接每个sheet。
3、循环每个sheet,然后通过concat函数把空DataFrame对象依次拼接每个sheet。
注意事项:
1、concat函数会默认把表头一致的列对齐,确保每个sheet的表头是一致的。
实现代码如下:
# -*- coding: utf-8 -*-
import pandas as pd
# 参数为None 代表读取所有sheet
df = pd.read_excel('kwd_city.xlsx',sheet_name=None)
# 获取所有sheet名字
# 如果read_excel参数不是None,则()为表头
sheet_names = list(())
# 创建空df用来连接
df_concat = ()
# 循环每个df拼接成一个
for sheet_name in sheet_names:
df_sheet = df[sheet_name]
df_concat = ([df_concat,df_sheet])
# 写入新的excel
df_concat.to_excel('kwd_city_new.xlsx',index=False)