Как объединить несколько файлов excel в один pandas

As mentioned in the comments, one error you are making is that you are looping over an empty list.

Here is how I would do it, using an example of having 5 identical Excel files that are appended one after another.

(1) Imports:

import os
import pandas as pd

(2) List files:

path = os.getcwd()
files = os.listdir(path)
files

Output:

['.DS_Store',
 '.ipynb_checkpoints',
 '.localized',
 'Screen Shot 2013-12-28 at 7.15.45 PM.png',
 'test1 2.xls',
 'test1 3.xls',
 'test1 4.xls',
 'test1 5.xls',
 'test1.xls',
 'Untitled0.ipynb',
 'Werewolf Modelling',
 '~$Random Numbers.xlsx']

(3) Pick out ‘xls’ files:

files_xls = [f for f in files if f[-3:] == 'xls']
files_xls

Output:

['test1 2.xls', 'test1 3.xls', 'test1 4.xls', 'test1 5.xls', 'test1.xls']

(4) Initialize empty dataframe:

df = pd.DataFrame()

(5) Loop over list of files to append to empty dataframe:

for f in files_xls:
    data = pd.read_excel(f, 'Sheet1')
    df = df.append(data)

(6) Enjoy your new dataframe. :-)

df

Output:

  Result  Sample
0      a       1
1      b       2
2      c       3
3      d       4
4      e       5
5      f       6
6      g       7
7      h       8
8      i       9
9      j      10
0      a       1
1      b       2
2      c       3
3      d       4
4      e       5
5      f       6
6      g       7
7      h       8
8      i       9
9      j      10
0      a       1
1      b       2
2      c       3
3      d       4
4      e       5
5      f       6
6      g       7
7      h       8
8      i       9
9      j      10
0      a       1
1      b       2
2      c       3
3      d       4
4      e       5
5      f       6
6      g       7
7      h       8
8      i       9
9      j      10
0      a       1
1      b       2
2      c       3
3      d       4
4      e       5
5      f       6
6      g       7
7      h       8
8      i       9
9      j      10

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Let us see how to join the data of two excel files and save the merged  data as a new Excel file.

    We have 2 files, registration details.xlsx and exam results.xlsx.

    registration details.xlsx

    We are having 7 columns in this file with 14 unique students details. Column names are as follows :

    • Admission Date
    • Name of Student
    • Gender
    • DOB
    • Student email Id
    • Enquiry No.
    • Registration No.

    exam results.xlsx

    We are having 7 columns in this file with 32 unique students’ details. Column names are as follows :

    • Registration No.
    • Name
    • No.of questions attempted
    • Correct
    • Incorrect
    • Marks Obtained
    • Percentage

    You can download these files from these links : registration details.xlsx and exam results.xlsx.

    Now, let’s see the common columns between these two files :

    So the common column between the excel files is REGISTRATION NO. So we need to merge these two files in such a way that the new excel file will only hold the required columns i.e. :

    Algorithm :

    1. Import the Pandas module.
    2. Read both the files using the read_excel() function.
    3. Combine them using the merge() function.
    4. Use the to_excel() function, to create the resultant file.

    import pandas

    f1 = pandas.read_excel("registration details.xlsx")

    f2 = pandas.read_excel("exam results.xlsx")

    f3 = f1[["REGISTRATION NO"

             "STUDENT EMAIL ID "]].merge(f2[["REGISTRATION NO"

                                             "Name", "Marks Obtained"

                                             "Percentage"]], 

                                         on = "REGISTRATION NO"

                                         how = "left")

    f3.to_excel("Results.xlsx", index = False)

    Output :

    Like Article

    Save Article

    • Редакция Кодкампа

    17 авг. 2022 г.
    читать 2 мин


    Часто вам может понадобиться импортировать и объединить несколько листов Excel в один кадр данных pandas.

    Например, предположим, что у вас есть следующая книга Excel с именем data.xlsx с тремя разными листами, каждый из которых содержит два столбца данных о баскетболистах:

    Мы можем легко импортировать и объединять каждый лист в один кадр данных pandas, используя функции pandas concat () и read_excel() , но сначала нам нужно убедиться, что xlrd установлен:

    pip install xlrd
    

    Как только это будет установлено, мы можем использовать следующий код для импорта и объединения этих трех листов в один DataFrame pandas:

    #load pandas library
    import pandas as pd
    
    #import and combine the three sheets into one pandas DataFrame
    df = pd.concat (pd.read_excel('data.xlsx', sheet_name= None ), ignore_index= True )
    
    #view DataFrame
    df
    
     player points
    0 A 12
    1 B 5
    2 C 13
    3 D 17
    4 E 27
    5 F 24
    6 G 26
    7 H 27
    8 I 27
    9 J 12
    10 K 9
    11 L 5
    12 M 5
    13 N 13
    14 O 17
    

    Как работает этот код

    Есть только две части, чтобы понять, как эта единственная строка кода может импортировать и объединять несколько листов Excel:

    1. Читать на всех листах.

    pd.read_excel('data.xlsx', sheet_name= None )
    

    Этот фрагмент кода читается на всех листах книги Excel. По умолчанию функция read_excel() читает только на первом листе, но, указав sheet_name=None , мы можем читать на каждом отдельном листе в книге Excel.

    2. Объедините все листы.

    pd.concat ( *DataFrames to concatenate* , ignore_index= True )
    

    Этот фрагмент кода просто объединяет все кадры данных с каждого листа Excel в один кадр данных pandas. Указав ignore_index=True , мы сообщаем pandas, что имена отдельных листов не важны.

    Обратите внимание, что этот код работает, только если все листы Excel имеют одинаковый формат. В этом примере на каждом листе было два столбца данных, и каждый столбец имел одно и то же имя, поэтому эта единственная строка кода работала так легко, чтобы объединить все листы Excel в один кадр данных pandas.

    Дополнительные ресурсы

    Полное руководство: как читать файлы Excel с помощью Pandas
    Как записать кадры данных Pandas в несколько листов Excel

    Recipe Objective

    In most of the big data scenarios , we need to merge multiple files or tables based on the various conditions to a unified data model for quicker data analysis purposes.in this recipe we are going to merge various excel files based on the certain conditions

    Master the Art of Data Cleaning in Machine Learning

    System requirements :

    • Install pandas python module as follows: pip install pandas
    • The below codes can be run in Jupyter notebook , or any python console
    • In this scenario we are going to use 3 excel files to perform joins Products dataset , Orders dataset , Customers dataset

    Table of Contents

    • Recipe Objective
      • System requirements :
      • Step 1: Import the modules
      • Step 2: Read the Excel Files
      • Step 3: Join operations on the Data frames
      • Step 4: write result to the csv file

    Step 1: Import the modules

    In this example we are going to use the pandas library , this library is used for data manipulation pandas data structures and operations for manipulating numerical tables and time series


    Import pandas as pd

    Step 2: Read the Excel Files

    In the below code we are going read the data from excel files, and create dataframes using pandas library.


    orders = pd. read_excel('orders.xlsx')
    products =pd.read_excel("products.xlsx")
    customers = pd.read_excel("customers.xlsx")

    Step 3: Join operations on the Data frames

    using the merge function in the pandas library , all database join operations between the pandas from the excel data. using the «how» parameter in the merge function we will perform the join operations like left, right,..etc.

    Left Join :


    import pandas as pd

    orders = pd. read_excel('orders.xlsx')
    products =pd.read_excel("products.xlsx")
    customers = pd.read_excel("customers.xlsx")

    result = pd.merge(orders,customers[["Product_id","Order_id","customer_name",'customer_email']],on='Product_id', how='left')
    result.head()

    Output of the above code:

    Inner Join :


    import pandas as pd

    orders = pd. read_excel('orders.xlsx')
    products =pd.read_excel("products.xlsx")
    customers = pd.read_excel("customers.xlsx")
    result= pd.merge(products,customers,on='Product_id',how='inner',indicator=True)
    result.head()

    Output of the above code:

    Right Join :


    import pandas as pd

    orders = pd. read_excel('orders.xlsx')
    products =pd.read_excel("products.xlsx")
    customers = pd.read_excel("customers.xlsx")

    result = pd.merge(orders, customers[["Product_id","Order_id","customer_name",'customer_email']],
    on='Product_id',
    how='right',
    indicator=True)
    result.head()

    Output of the above code:

    Outer Join :

    import pandas as pd

    orders = pd. read_excel('orders.xlsx')
    products =pd.read_excel("products.xlsx")
    customers = pd.read_excel("customers.xlsx")
    result= pd.merge(products,customers,on='Product_id',how='outer',indicator=True)
    result.head()

    Output of the above code:

    Step 4: write result to the csv file

    After getting the result write to the hdfs or local file


    import pandas as pd

    orders = pd. read_excel('orders.xlsx')
    products =pd.read_excel("products.xlsx")
    customers = pd.read_excel("customers.xlsx")

    result = pd.merge(orders,
    customers[["Product_id","Order_id","customer_name",'customer_email']],
    on='Product_id')
    result.head()
    # write the results to the hdfs/ local
    result.to_excel("Results.xlsx", index = False)

    Output of the above code : an excel file which will be written to current location of execution of the code and it looks like below

    Предположим, имеется куча книг Excel, все листы из которых надо объединить в один файл. Копировать руками долго и мучительно, поэтому имеет смысл использовать несложный макрос.

    Открываем книгу, куда хотим собрать листы из других файлов, входим в редактор Visual Basic (ALT+F11), добавляем новый пустой модуль (в меню Insert — Module) и копируем туда текст вот такого макроса:

    Sub CombineWorkbooks()
    Dim FilesToOpen
    Dim x As Integer

    Application.ScreenUpdating = False ‘отключаем обновление экрана для скорости

    ‘вызываем диалог выбора файлов для импорта
    FilesToOpen = Application.GetOpenFilename _
    (FileFilter:=»All files (*.*), *.*», _
    MultiSelect:=True, Title:=»Files to Merge»)

    If TypeName(FilesToOpen) = «Boolean» Then
    MsgBox «Не выбрано ни одного файла!»
    Exit Sub
    End If

    ‘проходим по всем выбранным файлам
    x = 1
    While x <= UBound(FilesToOpen)
    Set importWB = Workbooks.Open(Filename:=FilesToOpen(x))
    Sheets().Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
    importWB.Close savechanges:=False
    x = x + 1
    Wend

    Application.ScreenUpdating = True
    End Sub

    После этого можно вернуться в Excel и запустить созданный макрос через меню Сервис — Макрос — Макросы (Tools — Macro — Macros) или нажав ALT+F8. Отобразится диалоговое окно открытия файла, где необходимо указать один или несколько (удерживая CTRL или SHIFT) файлов, листы из которых надо добавить к текущей книге.
    PE

    Last Updated on April 9, 2023 by

    In this short tutorial, I’ll show you how to use Python to combine multiple Excel files into one master spreadsheet. Imagine that you have dozens of Excel files with the same data fields, and your job is to aggregate sheets from those files. Manually doing this job is super inefficient, and Python will save you a lot of time in the long run, so let’s all work smarter!

    Note that this article talks about appending Excel files with the same format/data fields. Merging multiple dataset is a different task.

    If you are new to Python, this series Integrate Python with Excel offers some tips on how to use Python to supercharge your Excel spreadsheets.

    The workflow

    To solve the problem, we’ll need to follow the below work flow:

    1. Identify the files we need to combine
    2. Get data from the file
    3. Move data from step 2) to a master dataset (we will call it “dataframe”)
    4. Report 2-3 for the number of files
    5. Save the master dataset into an Excel spreadsheet

    Import libraries

    Alright, let’s see how to code the above work flow in Python. For this exercise, we’ll need to use two Python libraries: os and pandas. If you want to follow along, feel free to grab the source code and files used in this tutorial from here. Although you can combine as many Excel files as you wish, we’ll use three files to demonstrate the process.

    If you need help with installing Python or libraries, here’s a guide on how to do that.

    os library gives a way of using operating system dependent functionalities. Such as manipulating folder and file paths. We use this library to get all the Excel file names, including their paths.

    pandas library is the gold standard for data analysis and manipulation. It is fast, powerful, and flexible. We use this library to load Excel data into Python, manipulate data, and recreate the master spreadsheet.

    We’ll start by importing these two libraries. Then find the current working directory, as well as all the file names within the directory.

    import os
    import pandas as pd
    cwd = os.path.abspath('') 
    files = os.listdir(cwd) 

    python code showing current working directory

    Getting current working directory and files within it

    The variable cwd shows the path to the current working directory, and the variable files is a list of all the file names within the current working directory. Notice there are non-Excel files, and we don’t want to open those, so we’ll handle that soon.

    Next, we create an empty dataframe df for storing the data for master spreadsheet. We loop through all the files within the current working directory, but only process the Excel files whose name ends with “.xlsx”. This is done by this line of code
    if file.endswith('.xlsx'):

    pd.read_excel() will read Excel data into Python and store it as a pandas DataFrame object. Be aware that this method reads only the first tab/sheet of the Excel file by default. If your Excel file contains more than 1 sheet, continue reading to the next section.

    df.append() will append/combine data from one file to another. Think about copying a block of data from one Excel file and pasting it into another. Instead of opening up Excel, data is stored inside your computer’s memory.

    df = pd.DataFrame()
    for file in files:
         if file.endswith('.xlsx'):
             df = df.append(pd.read_excel(file), ignore_index=True) 
    df.head()

    The above code does the following:

    1. Loop through all the files in the current working directory, determine if a file is Excel by checking the file name ends with “.xlsx”.
    2. If yes, read the file content (data), and append/add it to the master dataframe variable called df.
    3. Save the master dataframe into an Excel spreadsheet.

    We can examine the master dataframe by checking df.head(), which shows the first 5 rows of the data.

    python code showing the first 5 rows of data

    Checking the first 5 rows of data in the dataframe

    Seems good! Just another quick check to make sure we have loaded everything in the DataFrame. df.shape will show us the dimension (36 rows, 5 columns) of the data:

    python code showing the size of the master dataframe

    Everything looks good, so let’s output the data back into Excel. The last line df.to_excel() will do that.

    Combine multiple sheets from the same Excel file

    I talked about the two techniques to read multiple sheets from the same Excel file, so I won’t repeat it. However, I’ll walk through an example here with a slightly different setting.

    We have 2 files each contains a number of sheets. We don’t know how many sheets are in each file, but we know the format is the same for all sheets. Our goal is to aggregate all sheets into one spreadsheet (and one file).

    The workflow is similar:

    1. Get all Excel files
    2. Loop through the Excel files
    3. For each file, loop through all sheets
    4. Read each sheet into a dataframe, then combine all dataframes together.
    df_total = pd.DataFrame()
    for file in files:  # loop through Excel files
        if file.endswith('.xlsx'):
            excel_file = pd.ExcelFile(file)
            sheets = excel_file.sheet_names
            for sheet in sheets: # loop through sheets inside an Excel file
                df = excel_file.parse(sheet_name = sheet)
                df_total = df_total.append(df)
    df_total.to_excel('combined_file.xlsx')
    

    Putting it all together

    Below is the full code put together. 10 lines of code will help you combine all your Excel files or sheets into one master spreadsheet. Enjoy!

    import os
    import pandas as pd
    cwd = os.path.abspath('') 
    files = os.listdir(cwd)  
    
    ## Method 1 gets the first sheet of a given file
    df = pd.DataFrame()
    for file in files:
        if file.endswith('.xlsx'):
            df = df.append(pd.read_excel(file), ignore_index=True) 
    df.head() 
    df.to_excel('total_sales.xlsx')
    
    
    
    ## Method 2 gets all sheets of a given file
    df_total = pd.DataFrame()
    for file in files:                         # loop through Excel files
        if file.endswith('.xlsx'):
            excel_file = pd.ExcelFile(file)
            sheets = excel_file.sheet_names
            for sheet in sheets:               # loop through sheets inside an Excel file
                df = excel_file.parse(sheet_name = sheet)
                df_total = df_total.append(df)
    df_total.to_excel('combined_file.xlsx')

    Файлы к уроку:

    • Для спонсоров Boosty
    • Для спонсоров VK
    • YouTube
    • VK

    Ссылки:

    • Страница курса
    • Плейлист YouTube
    • Плейлист ВК

    Описание

    У нас есть несколько однообразных книг Excel. В каждой книге Excel находится несколько листов с единой структурой. Нам нужно одновременно объединить все книги и все листы в них в одну таблицу.

    Решим эту задачу с помощью модуля pandas.

    Решение

    Сначала импортируем нужные модули.

    # Импорт модулей
    import pandas as pd
    import os
    import glob

    Укажем директорию, в которой находятся файлы.

    # Сменим директорию
    os.chdir('data')

    Создадим список книг для объединения.

    # Список файлов Excel для объединения
    xl_files = glob.glob('*.xlsx')

    Создадим датафрейм, в который запишем таблицы.

    # Читаем каждую книгу объединяем все листы в один датафрейм
    combined = pd.DataFrame()

    Читаем каждый файл и объединяем все таблицы.

    # Цикл по файлам
    for xl_file in xl_files:
        # Создать объект ExcelFile
        xl_file_obj = pd.ExcelFile(xl_file)
        # Цикл по листам
        for sheet_name in xl_file_obj.sheet_names:
            # Прочитать нужный лист книги
            data = pd.read_excel(xl_file_obj,
                                 sheet_name=sheet_name)
            # Создадать столбец с названием книги
            data['workbook'] = xl_file
            # Создать столбец с названием листа
            data['sheet'] = sheet_name
            # Дописать в датафрейм combined
            combined = combined.append(data)

    Запишем результат в книгу Excel.

    combined.to_excel('sales_combined.xlsx',
                      index=False)

    Примененные функции

    • os.getcwd
    • os.chdir
    • glob.glob
    • pandas.ExcelFile
    • pandas.DataFrame
    • pandas.read_excel
    • pandas.DataFrame.append
    • pandas.DataFrame.to_excel

    Курс Python Практический

    Номер урока Урок Описание
    1 Python Практический. Скачиваем котировки В этом уроке мы научимся скачивать котировки с помощью модуля pandas_datareader.
    2 Python Практический. Объединить книги Excel В этом уроке мы объединим много Excel файлов в один CSV файл с помощью Python
    3 Python Практический. Объединить книги Excel Дополним урок по объединению большого количества XLSX файлов в один CSV при помощи Python. Добавим Progress Bar и вывод времени начала обработки каждого файла.
    4 Python Практический. Создать Progress Bar В этом уроке мы научимся создавать Progress Bar в Python. Для этого воспользуемся модулем tqdm.
    5 Python Практический. Объединить листы книги Excel Объединим множество листов одной книги Excel по вертикали.
    6 Python Практический. Объединить книги Excel и листы в них Как объединить книги Excel и все листы в них в одну таблицу.
    7 Python Практический. Объединить множество CSV Объединим множество CSV файлов по вертикали в один CSV файл.
    8 Python Практический. Таблицы из множества интернет-страниц Извлечем таблицу из множества веб-страниц и объединим по вертикали.
    9 Python Практический. Многостраничное извлечение таблиц с Requests и BS4 В этом уроке мы с помощью Python модулей Requests и BS4 извлечем таблицу из множества web-страниц, потом все эти таблицы объединим по вертикали в одну и запишем результат в Excel файл.
    10 Python Практический. Скрапинг/Парсинг сайтов с Selenium и BS4 В этом уроке мы будем скрапить/парсить веб сайт с Python модулями Selenium и BF4.
    11 Python Практический. Автоматизация браузера Python Selenium, Скрапинг, скачивание выписок ЕГРЮЛ В этом уроке мы познакомимся с модулем Selenium для Python. Он позволяет автоматизировать работу браузера, например, открывать веб-страницы, заполнять формы, получать содержимое блоков и скачивать файлы. Мы изучим основы Selenium на примере получения данных ЕГРЮЛ по ИНН и автоматическому скачиванию выписок ЕГРЮЛ.
    12 Python Практический. Множественная замена текста с Pandas В этом уроке мы выполним множественную замена текста с помощью модуля Pandas

    Понравилась статья? Поделить с друзьями:

    А вот еще интересные статьи:

  • Как объединить несколько условий если в excel
  • Как объединить много ячеек в excel без потери текста
  • Как объединить несколько таблиц в одну в excel в одну сводную таблицу
  • Как объединить много файлов excel в один лист
  • Как объединить несколько таблиц в одну в excel power query

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии