Excel文件被覆盖而不是concat-Python-Pandas [英] Excel file overwritten instead of concat - Python - Pandas

查看:157
本文介绍了Excel文件被覆盖而不是concat-Python-Pandas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下脚本将其中的所有excel文件和工作表联系在一起.可以,但是每个文件都会覆盖excel文件c.xlsx,因此只能隐藏最后一个excel文件,不确定为什么?

I'm trying to contact all excel files and worksheets in them into one using the below script. It kinda works but then the excel file c.xlsx is overwritten per file, so only the last excel file is concated not sure why?

import pandas as pd
import os
import ntpath
import glob

dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)
cdf = None
for excel_names in glob.glob('*.xlsx'):
    print(excel_names)
    df = pd.read_excel(excel_names, sheet_name=None, ignore_index=True)
    cdf = pd.concat(df.values())
    cdf.to_excel("c.xlsx", header=False, index=False)

推荐答案

想法是在列表理解中创建DataFrame的列表,但是因为必须使用orderdict循环进行concat,然后再次使用concat最终的大型DataFrame:

Idea is create list of DataFrames in list comprehension, but because working with orderdict is necessary concat in loop and then again concat for one big final DataFrame:

cdf = [pd.read_excel(excel_names, sheet_name=None, ignore_index=True).values() 
       for excel_names in glob.glob('files/*.xlsx')]

df = pd.concat([pd.concat(x) for x in cdf], ignore_index=True)
#print (df)

df.to_excel("c.xlsx", index=False)

这篇关于Excel文件被覆盖而不是concat-Python-Pandas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆