【问题标题】:Python/pandas For Loop with Excel, Merge multiple Workbooks (Single Column) to Search ListPython/pandas For Loop 与 Excel,合并多个工作簿(单列)到搜索列表
【发布时间】:2020-05-13 22:00:45
【问题描述】:

我可以在 Excel VBA 上使用它,但在 python 上不行...

如果有人可以提供帮助,不胜感激!这是我目前所拥有的。

列名“搜索”是我要合并的通用索引。

import pandas as pd
import os

l = []
for root, dirs, files in os.walk(r"D:/"):
    for file in files:
        if file.endswith(".xlsx"):
             l.append(os.path.join(root, file))


search = 'Search List.xlsx'
source = pd.read_excel(open(search,'rb'), sheet_name=0)
source.set_index("Search", inplace = True)


for i in range(0, len(l)):
    path = l[i]
    df = pd.read_excel(open(path,'rb'), sheet_name=0)
    df.rename(columns={ df.columns[3]: "Search" }, inplace = True)
    df.set_index("Search",inplace = True)

final = pd.merge(source, df, on = ['Search'], how = 'left')

Os.walk 给我一个以 xlsx 结尾的文件的路径,并创建一个列表?


['D:/搜索\查找列表 1.xlsx', 'D:/搜索\查找列表 2.xlsx', 'D:/搜索\查找列表 3.xlsx', 'D:/Search\查找列表 4.xlsx']


一旦我有了路径列表,我需要一次打开一个,与匹配列搜索的“源”列表合并。一个一个,我需要合并剩余的excel文件。这有意义吗?

我如何for循环读取excel,合并匹配的列,然后移动到列表的下一个迭代。

我真的很迷茫

感谢您的帮助!

【问题讨论】:

  • 我假设除源列表之外的所有其他文件都具有相同的列数和名称。我建议您阅读所有这些文件,将它们合并,最后与源文件合并。 pd.concat([所有其他文件]),然后 source.merge(bla, left_on=..., right_on='search') 这可能会有所帮助:pandas.pydata.org/pandas-docs/stable/user_guide/…
  • 嗨,萨米。感谢您的输入和链接。我通过并找到了解决方案!

标签: python excel pandas loops


【解决方案1】:

在 Sammy 的建议下找到了解决方案。我连接列表中的所有 Excel 文件,然后根据需要调整数据,然后与原始搜索列表合并。

import pandas as pd
import os

l = []


for root, dirs, files in os.walk(r"D:/Search"):
    for file in files:
        if file.endswith(".xlsx"):

                df = pd.read_excel(open(file,'rb'), sheet_name=0, header = 0)
                df.rename(columns={ df.columns[3]: "Search" }, inplace = True)
                df["Path"] = file
                l.append(df)

frame = pd.concat(l, axis=0, ignore_index=True)
frame = frame.drop([frame.columns[0] , frame.columns[1], frame.columns[2], frame.columns[4]],  axis='columns')
frame.set_index("Search",inplace = True)


search = 'Search List.xlsx'
source = pd.read_excel(open(search,'rb'), sheet_name=0)
source.set_index("Search", inplace = True)



final = pd.merge(source, frame, on = ['Search'], how = 'left')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多