简体   繁体   English

将熊猫数据框写入一个 excel 文件

[英]Writing pandas dataframe into one excel file

I'm trying to write the data from 2 excel files into one file.我正在尝试将 2 个 excel 文件中的数据写入一个文件。 Of course the code below only writes the data from the first sheet into the consolidated sheet because the loop ends when writing the data from the first sheet.当然,下面的代码只将第一张工作表中的数据写入合并工作表中,因为从第一张工作表写入数据时循环结束。 I think the solution is to keep the data from the first sheet, then append and then write to the sheet.我认为解决方案是保留第一张工作表中的数据,然后追加并写入工作表。 But how?但是如何? Today I'm too dumb finding the solution.今天我太愚蠢了找到解决方案。

import pandas as pd

xlsInPath = "some path to sheets but all have one sheet with name 2019"
xlsFiles = ['test1.xlsx', 'test2.xlsx']
sheetName = ['2019']

df = pd.DataFrame({})

for xlsF in xlsFiles:
    FN = xlsInPath + xlsF
    print(FN)
    data1 = pd.read_excel(FN, sheet_name=sheetName, header=1, skiprows=0, engine='xlrd')
    print(data1)
    df.append(data1, ignore_index=True)
    df = pd.concat(data1)
    df.to_excel (r'C:\\Users\\A\\out\\Name.xlsx', sheet_name='Sheet_name_1', index=False, header=None)

I think that your problem is that you are writing the dataframe to excel in the loop.我认为您的问题是您正在编写数据框以在循环中表现出色。 Move the last line in your loop outside the loop, then you will be pasting the entire dataframe into the spreadsheet at once instead of one sheet at a time.将循环中的最后一行移到循环外,然后您将一次将整个数据框粘贴到电子表格中,而不是一次粘贴一张工作表。 There may or may not be another problem in your code, but I would at least try that.您的代码中可能有也可能没有其他问题,但我至少会尝试一下。

The solution is:解决办法是:

import pandas as pd

xlsInPath = "C:\\Users\\in\\"
xlsOutPath = "C:\\Users\\out\\"
xlsInFiles = ['test1.xlsx', 'test2.xlsx']
xlsOutFile = 'ConcatResult.xlsx'

sheetName = '2019'  
# must be string if only 1 worksheet otherwise a list of strings

df = pd.DataFrame()

for xlsF in xlsInFiles:
    FN = xlsInPath + xlsF
    print(FN)
    xd = pd.read_excel(FN, sheet_name=sheetName, header=0, skiprows=0, engine='xlrd')
    # needs header here line 0 first line to recognize the equal columns
    print('##XD\n', xd)

    df = pd.concat([df, xd], axis=0, ignore_index=True, sort=False)  
    # needs a list of concatanable DataFrames

print('##DF\n', df)
df.to_excel(r''+xlsOutPath+xlsOutFile, sheet_name=sheetName, index=False, header=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM