【问题标题】:Appending data from multiple excel files into a single excel file without overwriting using python pandas将来自多个 excel 文件的数据附加到单个 excel 文件中而不使用 python pandas 覆盖
【发布时间】:2020-11-16 18:16:46
【问题描述】:

下面是我当前的代码。

我从多个 (~30) excel 文件中提取了特定范围的单元格(来自特定工作表)。我试图从所有这些文件中提取这些信息,以编译成一个新文件,每次都附加到该文件。我将暂时手动清理目标文件,因为我会改进这个脚本。

我目前拥有的单张工作正常,但每次我将新文件添加到读入列表时都会覆盖我的目标。

我尝试在函数末尾添加 mode = 'a' 和几种不同的连接方式。

import pandas as pd

def excel_loader(fname, sheet_name, new_file):
    xls = pd.ExcelFile(fname)
    df1 = pd.read_excel(xls, sheet_name, nrows = 20)
    print(df1[1:15])
    writer = pd.ExcelWriter(new_file)
    df1.insert(51, 'Original File', fname)
    df1.to_excel(new_file)

names = ['sheet1.xlsx', 'sheet2.xlsx']
destination = 'destination.xlsx'

for name in names:
    excel_loader(name, 'specific_sheet_name', destination)

感谢您提前提供的任何帮助,似乎无法在此处找到此确切情况的答案。干杯。

【问题讨论】:

  • 据我所知,您不能使用 pandas 修改 excel 文件,您需要另一个库,如 xlwings,最好的办法是将 excel 内容加载到数据框中并只做一个写
  • 我曾认为修改 Excel 文件是 pandas 相当标准的用途。我可以将数据添加到当前使用此行的新列中:df1.insert(51, 'Original File', fname),它只是添加了一个标题为“原始文件”的列,并为其余行添加了原始文件名。不过我会查看xlwings
  • Pandas 代表 Panel Data,因此能够读写 excel 文件正是您所期望的 :)

标签: python-3.x excel pandas


【解决方案1】:

理想情况下,您希望遍历文件并将数据读入列表,然后连接各个数据帧,然后写入新数据帧。这假设要提取的数据大小/形状相同,并且工作表名称相同。如果工作表名称发生变化,请查看 zip() 函数以发送文件名/工作表名元组。

这应该让你开始:

names = ['sheet1.xlsx', 'sheet2.xlsx']
destination = 'destination.xlsx'

#read all files first
df_hold_list = []
for name in names:
    xls = pd.ExcelFile(name)
    df = pd.read_excel(xls, sheet_name, nrows = 20)
    df_hold_list.append(df)

#concatenate dfs 
df1 = pd.concat(df_hold_list, axis=1) # axis is 1 or 0 depending on how you want to cancatenate (horizontal vs vertical)

#write new file - may have to correct this piece - not sure what functions these are
writer = pd.ExcelWriter(destination)
df1.to_excel(destination)

【讨论】:

  • 只是想让你知道,通过这个我能够得到我正在寻找的结果。非常感谢对此的帮助。干杯的朋友!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
  • 2018-11-22
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 2021-08-29
相关资源
最近更新 更多