Pandas dataset to excel

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

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


Часто вас может заинтересовать экспорт фрейма данных pandas в Excel. К счастью, это легко сделать с помощью функции pandas to_excel() .

Чтобы использовать эту функцию, вам нужно сначала установить openpyxl , чтобы вы могли записывать файлы в Excel:

pip install openpyxl

В этом руководстве будет объяснено несколько примеров использования этой функции со следующим фреймом данных:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
 'assists': [5, 7, 7, 9, 12],
 'rebounds': [11, 8, 10, 6, 6]}) 

#view DataFrame
df

 points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6

Пример 1: базовый экспорт

В следующем коде показано, как экспортировать DataFrame по определенному пути к файлу и сохранить его как mydata.xlsx :

df.to_excel (r'C:UsersZachDesktopmydata.xlsx')

Вот как выглядит фактический файл Excel:

Пример 2: Экспорт без индекса

В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и удалить столбец индекса:

df.to_excel (r'C:UsersZachDesktopmydata.xlsx', index= False )

Вот как выглядит фактический файл Excel:

Пример 3: Экспорт без индекса и заголовка

В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и удалить столбец индекса и строку заголовка:

df.to_excel (r'C:UsersZachDesktopmydata.xlsx', index= False, header= False )

Вот как выглядит фактический файл Excel:

Пример 4: Экспорт и имя листа

В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и назвать рабочий лист Excel:

df.to_excel (r'C:UsersZachDesktopmydata.xlsx', sheet_name='this_data')

Вот как выглядит фактический файл Excel:

Полную документацию по функции to_excel() можно найти здесь .

You can export Pandas DataFrame to an Excel file using to_excel.

Here is a template that you may apply in Python to export your DataFrame:

df.to_excel(r'Path where the exported excel will be storedFile Name.xlsx', index=False)

And if you want to export your DataFrame to a specific Excel Sheet, then you may use this template:

df.to_excel(r'Path of excelFile Name.xlsx', sheet_name='Your sheet name', index=False)

Note: you’ll have to install openpyxl if you get the following error:

ModuleNotFoundError: No module named ‘openpyxl’

You may then use PIP to install openpyxl as follows:

pip install openpyxl

In the next section, you’ll see a simple example, where:

  • A DataFrame will be created from scratch
  • Then, the DataFrame will be exported to an Excel file

Let’s say that you have the following dataset about products and their prices:

product_name price
computer 1200
printer 150
tablet 300
monitor 450

The ultimate goal is to export that dataset into Excel.

But before you export that data, you’ll need to create a DataFrame in order to capture this information in Python.

You may then use the following syntax to create the DataFrame:

import pandas as pd

data = {'product_name': ['computer', 'printer', 'tablet', 'monitor'],
        'price': [1200, 150, 300, 450]
        }

df = pd.DataFrame(data)

print(df)

This is how the DataFrame would look like:

  product_name  price
0     computer   1200
1      printer    150
2       tablet    300
3      monitor    450

Next, you’ll need to define the path where you’d like to store the exported Excel file.

For example, the path below will be used to store the exported Excel file (note that you’ll need to adjust the path to reflect the location where the Excel file will be stored on your computer):

r‘C:UsersRonDesktopexport_dataframe.xlsx’

Notice that 3 components were highlighted in relation to that path:

  • In yellow, the ‘r’ character is placed before the path to avoid unicode error
  • In blue, the file name to be created is specified. You may type a different file name based on your needs
  • In green, the file type is specified. Since we are dealing with an Excel file, the file type would be ‘.xlsx’ for the latest version of Excel

Putting everything together, here is the full Python code to export Pandas DataFrame to an Excel file:

import pandas as pd

data = {'product_name': ['computer', 'printer', 'tablet', 'monitor'],
        'price': [1200, 150, 300, 450]
        }

df = pd.DataFrame(data)

df.to_excel(r'C:UsersRonDesktopexport_dataframe.xlsx', index=False)

Finally, run the above code in Python (adjusted to your path), and you’ll notice that a new Excel file (called export_dataframe) would be created at the location that you specified.

Note that if you wish to include the index, then simply remove “, index=False” from your code.

Additional Resources

You just saw how to export Pandas DataFrame to an Excel file. At times, you may need to export Pandas DataFrame to a CSV file. The concept would be similar in such cases.

You may also want to check the Pandas Documentation for additional information about df.to_excel.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Let us see how to export a Pandas DataFrame to an Excel file. 

    Algorithm:

    1. Create the DataFrame.
    2. Determine the name of the Excel file.
    3. Call to_excel() function with the file name to export the DataFrame.

    Example 1:

    Python3

    import pandas as pd

    marks_data = pd.DataFrame({'ID': {0: 23, 1: 43, 2: 12,

                                     3: 13, 4: 67, 5: 89,

                                     6: 90, 7: 56, 8: 34},

                              'Name': {0: 'Ram', 1: 'Deep',

                                       2: 'Yash', 3: 'Aman',

                                       4: 'Arjun', 5: 'Aditya',

                                       6: 'Divya', 7: 'Chalsea',

                                       8: 'Akash' },

                              'Marks': {0: 89, 1: 97, 2: 45, 3: 78,

                                        4: 56, 5: 76, 6: 100, 7: 87,

                                        8: 81},

                              'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C',

                                        4: 'E', 5: 'C', 6: 'A', 7: 'B',

                                        8: 'B'}})

    file_name = 'MarksData.xlsx'

    marks_data.to_excel(file_name)

    print('DataFrame is written to Excel File successfully.')

    Output:

    DataFrame is written to Excel File successfully.

    The Excel file is:

    Example 2: We can also first use the ExcelWriter() method to save it.

    Python3

    import pandas as pd

    cars_data = pd.DataFrame({'Cars': ['BMW', 'Audi', 'Bugatti'

                                       'Porsche', 'Volkswagen'],

                              'MaxSpeed': [220, 230, 240, 210, 190],

                              'Color': ['Black', 'Red', 'Blue'

                                        'Violet', 'White']})

    datatoexcel = pd.ExcelWriter('CarsData1.xlsx')

    cars_data.to_excel(datatoexcel)

    datatoexcel.save()

    print('DataFrame is written to Excel File successfully.')

    Output:

    DataFrame is written to Excel File successfully.

    Like Article

    Save Article

    In this post, you will learn –

    1 . How to write a pandas dataframe to a excel file.

    2 . How to write specific columns to a excel file.

    3. How to write a pandas dataframes to multiple excel sheets using for loop.

    Let’s read the data to work with. If you want to follow along then download this file – click to download sales data.

    And before we do anything, you have to also install the openpyxl library to read and write excel file in pandas.

    # to install
    pip install openpyxl

    We will read three data from the sales excel file to work with.

    sales = pd.read_excel('sales_data.xlsx', sheet_name='Sales')
    purchase = pd.read_excel('sales_data.xlsx', sheet_name='Purchase Orders 1')
    select = pd.read_excel('sales_data.xlsx', sheet_name='Select')

    sales –

    purchase –

    select –

    To write a pandas dataframe to an excel file, we use the DataFrame.to_excel() method in pandas.

    Let’s say that you want to write the sales data to a new excel file. To do that, you will write.

    sales.to_excel('sales_output.xlsx')

    By default, the data will be named as sheet1, sheet2 etc. If you want, you can also name the sheet using the sheet_name parameter.

    sales.to_excel('sales_output2.xlsx', sheet_name='Sales')

    And if you look at the output, you will see that pandas have added the index of the dataframe to the excel file along with the data. If you want to get rid of this index, you need to set the index parameter to index=False.

    sales.to_excel('sales_output3.xlsx', sheet_name='Sales', index=False)

    2 . How to write specific columns to a excel file.

    Sometimes, you may want to write only specific columns and ignore all the other columns. To do that you can use the columns parameter.

    Let’s say you only want to include all the columns except the Date column in the sales data.

    cols = ['Product ID', 'Branch ID', 'Price', 'Quantity']
    
    sales.to_excel('sales_output4.xlsx', sheet_name='Sales', 
                   index=False, columns=cols)

    3. How to write a pandas dataframes to multiple excel sheets using for loop.

    Let’s say that you want to write all the 3 dataframe into a single excel file. To do that you will write –

    with pd.ExcelWriter('sales_new.xlsx') as writer:
        sales.to_excel(writer, sheet_name='sales')
        purchase.to_excel(writer, sheet_name='purchase')
        select.to_excel(writer, sheet_name='select')

    1 . Pandas – read_excel() – How to read Excel file in python

    2 . Pandas read_csv() – read a csv file in Python

    3 . Pandas to_csv – write a dataframe to a csv file

    Время чтения 4 мин.

    Python Pandas — это библиотека для анализа данных. Она может читать, фильтровать и переупорядочивать небольшие и большие наборы данных и выводить их в различных форматах, включая Excel. ExcelWriter() определен в библиотеке Pandas.

    Содержание

    1. Что такое функция Pandas.ExcelWriter() в Python?
    2. Синтаксис
    3. Параметры
    4. Возвращаемое значение
    5. Пример программы с Pandas ExcelWriter()
    6. Что такое функция Pandas DataFrame to_excel()?
    7. Запись нескольких DataFrames на несколько листов
    8. Заключение

    Метод Pandas.ExcelWriter() — это класс для записи объектов DataFrame в файлы Excel в Python. ExcelWriter() можно использовать для записи текста, чисел, строк, формул. Он также может работать на нескольких листах.Для данного примера необходимо, чтоб вы установили на свой компьютер библиотеки Numpy и Pandas.

    Синтаксис

    pandas.ExcelWriter(path, engine= None, date_format=None, datetime_format=None, mode=w,**engine_krawgs)

    Параметры

    Все параметры установлены на значения по умолчанию.

    Функция Pandas.ExcelWriter() имеет пять параметров.

    1. path: имеет строковый тип, указывающий путь к файлу xls или xlsx.
    2. engine: он также имеет строковый тип и является необязательным. Это движок для написания.
    3. date_format: также имеет строковый тип и имеет значение по умолчанию None. Он форматирует строку для дат, записанных в файлы Excel.
    4. datetime_format: также имеет строковый тип и имеет значение по умолчанию None. Он форматирует строку для объектов даты и времени, записанных в файлы Excel.
    5. Mode: это режим файла для записи или добавления. Его значение по умолчанию — запись, то есть ‘w’.

    Возвращаемое значение

    Он экспортирует данные в файл Excel.

    Пример программы с Pandas ExcelWriter()

    Вам необходимо установить и импортировать модуль xlsxwriter. Если вы используете блокнот Jupyter, он вам не понадобится; в противном случае вы должны установить его.

    Напишем программу, показывающую работу ExcelWriter() в Python.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    import pandas as pd

    import numpy as np

    import xlsxwriter

    # Creating dataset using dictionary

    data_set = {

        ‘Name’: [‘Rohit’, ‘Arun’, ‘Sohit’, ‘Arun’, ‘Shubh’],

        ‘Roll no’: [’01’, ’02’, ’03’, ’04’, np.nan],

        ‘maths’: [’93’, ’63’, np.nan, ’94’, ’83’],

        ‘science’: [’88’, np.nan, ’66’, ’94’, np.nan],

        ‘english’: [’93’, ’74’, ’84’, ’92’, ’87’]}

    # Converting into dataframe

    df = pd.DataFrame(data_set)

    # Writing the data into the excel sheet

    writer_obj = pd.ExcelWriter(‘Write.xlsx’,

                                engine=‘xlsxwriter’)

    df.to_excel(writer_obj, sheet_name=‘Sheet’)

    writer_obj.save()

    print(‘Please check out the Write.xlsx file.’)

    Выход:

    Please check out the Write.xlsx file.

    Содержимое файла Excel следующее.

    Метод ExcelWriter()

    В приведенном выше коде мы создали DataFrame, в котором хранятся данные студентов. Затем мы создали объект для записи данных DataFrame на лист Excel, и после записи данных мы сохранили лист. Некоторые значения в приведенном выше листе Excel пусты, потому что в DataFrame эти значения — np.nan. Чтобы проверить данные DataFrame, проверьте лист Excel.

    Что такое функция Pandas DataFrame to_excel()?

    Функция Pandas DataFrame to_excel() записывает объект на лист Excel. Мы использовали функцию to_excel() в приведенном выше примере, потому что метод ExcelWriter() возвращает объект записи, а затем мы используем метод DataFrame.to_excel() для его экспорта в файл Excel.

    Чтобы записать один объект в файл Excel .xlsx, необходимо только указать имя целевого файла. Для записи на несколько листов необходимо создать объект ExcelWriter с именем целевого файла и указать лист в файле для записи.

    На несколько листов можно записать, указав уникальное имя листа. При записи всех данных в файл необходимо сохранить изменения. Обратите внимание, что создание объекта ExcelWriter с уже существующим именем файла приведет к удалению содержимого существующего файла.

    Мы также можем написать приведенный выше пример, используя Python с оператором.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    import pandas as pd

    import numpy as np

    import xlsxwriter

    # Creating dataset using dictionary

    data_set = {

        ‘Name’: [‘Rohit’, ‘Arun’, ‘Sohit’, ‘Arun’, ‘Shubh’],

        ‘Roll no’: [’01’, ’02’, ’03’, ’04’, np.nan],

        ‘maths’: [’93’, ’63’, np.nan, ’94’, ’83’],

        ‘science’: [’88’, np.nan, ’66’, ’94’, np.nan],

        ‘english’: [’93’, ’74’, ’84’, ’92’, ’87’]}

    # Converting into dataframe

    df = pd.DataFrame(data_set)

    with pd.ExcelWriter(‘WriteWith.xlsx’, engine=‘xlsxwriter’) as writer:

        df.to_excel(writer, sheet_name=‘Sheet’)

    print(‘Please check out the WriteWith.xlsx file.’)

    Выход:

    Please check out the WriteWith.xlsx file.

    Вы можете проверить файл WriteWith.xlsx и просмотреть его содержимое. Это будет то же самое, что и файл Write.xlsx.

    Запись нескольких DataFrames на несколько листов

    В приведенном выше примере мы видели только один лист для одного фрейма данных. Мы можем написать несколько фреймов с несколькими листами, используя Pandas.ExcelWriter.

    Давайте напишем пример, в котором мы создадим три DataFrames и сохраним эти DataFrames в файле multiplesheet.xlsx с тремя разными листами.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    import pandas as pd

    import numpy as np

    import xlsxwriter

    # Creating dataset using dictionary

    data_set = {

        ‘Name’: [‘Rohit’, ‘Arun’, ‘Sohit’, ‘Arun’, ‘Shubh’],

        ‘Roll no’: [’01’, ’02’, ’03’, ’04’, np.nan],

        ‘maths’: [’93’, ’63’, np.nan, ’94’, ’83’],

        ‘science’: [’88’, np.nan, ’66’, ’94’, np.nan],

        ‘english’: [’93’, ’74’, ’84’, ’92’, ’87’]}

    data_set2 = {

        ‘Name’: [‘Ankit’, ‘Krunal’, ‘Rushabh’, ‘Dhaval’, ‘Nehal’],

        ‘Roll no’: [’01’, ’02’, ’03’, ’04’, np.nan],

        ‘maths’: [’93’, ’63’, np.nan, ’94’, ’83’],

        ‘science’: [’88’, np.nan, ’66’, ’94’, np.nan],

        ‘english’: [’93’, ’74’, ’84’, ’92’, ’87’]}

    data_set3 = {

        ‘Name’: [‘Millie’, ‘Jane’, ‘Michael’, ‘Bobby’, ‘Brown’],

        ‘Roll no’: [’01’, ’02’, ’03’, ’04’, np.nan],

        ‘maths’: [’93’, ’63’, np.nan, ’94’, ’83’],

        ‘science’: [’88’, np.nan, ’66’, ’94’, np.nan],

        ‘english’: [’93’, ’74’, ’84’, ’92’, ’87’]}

    # Converting into dataframe

    df = pd.DataFrame(data_set)

    df2 = pd.DataFrame(data_set2)

    df3 = pd.DataFrame(data_set3)

    with pd.ExcelWriter(‘multiplesheet.xlsx’, engine=‘xlsxwriter’) as writer:

        df.to_excel(writer, sheet_name=‘Sheet’)

        df2.to_excel(writer, sheet_name=‘Sheet2’)

        df3.to_excel(writer, sheet_name=‘Sheet3’)

    print(‘Please check out the multiplesheet.xlsx file.’)

    Выход:

    Запись нескольких DataFrames на несколько листов

    Вы можете видеть, что есть три листа, и каждый лист имеет разные столбцы имени.

    Функция to_excel() принимает имя листа в качестве параметра, и здесь мы можем передать три разных имени листа, и этот DataFrame сохраняется на соответствующих листах.

    Заключение

    Как использовать метод Pandas.ExcelWriter в Python

    Если вы хотите экспортировать Pandas DataFrame в файлы Excel, вам нужен только класс ExcelWriter(). Класс ExcelWrite() предоставляет объект записи, а затем мы можем использовать функцию to_excel() для экспорта DataFrame в файл Excel.

    Readers of this blog know that we are pretty big on finding ways to automate mundane and boring tasks. Python is great for automation, specially when it pertains to the Data Analysis domain.

    Lately, we are increasingly spending more an more time with the Pandas data Analysis library, and using it for data munging and visualization. We rather work in Python instead of dealing with the complexity of Excel Visual Basic for Applications (VBA) when manipulating data.

    That said, there are situations in which we choose to feed data from Pandas back into an Excel workbook. This allows us to combine Python and Pandas flexibility and speed with great visualization capabilities and the obvious ubiquity of Excel.

    Today we’ll show you how to write and export data from a Pandas DataFrame to an Excel file (xlsx). We’ll deal with two scenarios:

    • Save a Pandas DataFrame to one Excel worksheet.
    • Write Pandas DataFrames to multiple worksheets in a workbook.

    Note: This tutorial requires some basic knowledge of Python programming and specifically the Pandas library.

    Export and Write Pandas DataFrame to Excel

    Here’s the process in a nutshell:

    • First off, ensure that you have installed the pandas, openpyxl and xlsxwriter libraries into your environment. Here’s how to install Pandas in your Python development environment.
    • Initialize / Load data your Pandas DataFrame.
    • Use the DataFrame.to_excel method to export your data

    Load add-on libraries

    Before we start, we’ll need to import a few libraries into Python as shown below. Go ahead and type this Python 3 code into you favorite Python editor.

    import pandas as pd
    import openpyxl
    import xlsxwriter

    Defining our DataFrame

    Now let’s create the data that we’ll be using in this tutorial

    # define data as a dictionary
    data = ({"language": [ "Python", "C-Sharp", "Javascript","PHP"] ,
             "avg_salary": [120, 100, 120, 80],
              "applications": [10,15,14,20]})
    
    # Create a Pandas DataFrame out of a Python dictionary
    df = pd.DataFrame.from_dict(data)
    # look at the Data
    print(df.head())
    language avg_salary applications
    0 Python 120 10
    1 C-Sharp 100 15
    2 Javascript 120 14
    3 PHP 80 20

    Note: If you want to learn how to aggregate Data in Python you can look into our tutorial on grouping Python data according to one or multiple columns.

    Pandas export to new and existing Excel xls and xlsx files

    Now, we would like to export the DataFrame that we just created to an Excel workbook. Pandas has a very handy to_excel method that allows to do exactly that. Let’s use it:

    df.to_excel("languages.xlsx") 

    The code will create the languages.xlsx file and export the dataset into Sheet1

    Note: In case that you don’t have the openpyxl package installed in your Python environment, you’ll get the following error: ModuleNotFoundError: No module named ‘openpyxl’ .

    The solution is relatively simple: from your terminal or if you are using Anaconda, from the Anaconda Navigator, type: pip install openpyxl. Then re-run your code again.

    If you want to get more fancy you can use the parameters of the to_excel method to customize your data transfer. In our case we set the sheet name, chose not to export the DataFrame index picked the columns to export and even define frozen panes in the worksheet.

    df.to_excel("languages1.xlsx", sheet_name="Languages", index=False, , freeze_panes=(1,1), columns=["avg_salary", "language"])

    Python to Export Pandas DataFrames to multiple sheets

    So far so good, but what if we would like to import data into several worksheets? That’s possible as well, although a bit more elaborated. Note the usage of the xlsxwriter Python library.

    We’ll first split our data to three different DataFrames:

    #we define three lists
    S1= data["language"]
    S2= data["avg_salary"]
    S3= data["applications"]
    
    # We then create three dataframes
    df1=pd.DataFrame(S1, columns=["language"])
    df2=pd.DataFrame(S2 , columns=["avg_salary"])
    df3=pd.DataFrame(S3, columns=["applications"])
    
    # We then group the dataframes into a list for more efficient processing 
    dflist= [df1,df2,df3]

    Now we’ll import multiple dataframes into Excel (in this case our three dfs to three different worksheets).

    # We'll define an Excel writer object and the target file
    Excelwriter = pd.ExcelWriter("languages_multiple.xlsx",engine="xlsxwriter")
    
    #We now we'll loop the list of dataframes
    for i, df in enumerate (dflist):
        df.to_excel(Excelwriter, sheet_name="Sheet" + str(i+1),index=False)
    #And finally we save the file
    Excelwriter.save()

    Voi’la, now go ahead to your directory and look into the languages_multiple.xlsx file. You are done :-).

    Write Excel with Python Pandas. You can write any data (lists, strings, numbers etc) to Excel, by first converting it into a Pandas DataFrame and then writing the DataFrame to Excel.

    To export a Pandas DataFrame as an Excel file (extension: .xlsx, .xls), use the to_excel() method.

    Related course: Data Analysis with Python Pandas

    installxlwt, openpyxl

    to_excel() uses a library called xlwt and openpyxl internally.

    • xlwt is used to write .xls files (formats up to Excel2003)
    • openpyxl is used to write .xlsx (Excel2007 or later formats).

    Both can be installed with pip. (pip3 depending on the environment)

    1
    2
    $ pip install xlwt
    $ pip install openpyxl

    Write Excel

    Write DataFrame to Excel file

    Importing openpyxl is required if you want to append it to an existing Excel file described at the end.
    A dataframe is defined below:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import pandas as pd
    import openpyxl

    df = pd.DataFrame([[11, 21, 31], [12, 22, 32], [31, 32, 33]],
    index=['one', 'two', 'three'], columns=['a', 'b', 'c'])

    print(df)




    You can specify a path as the first argument of the to_excel() method.

    Note: that the data in the original file is deleted when overwriting.

    The argument new_sheet_name is the name of the sheet. If omitted, it will be named Sheet1.

    1
    df.to_excel('pandas_to_excel.xlsx', sheet_name='new_sheet_name')

    Python Write Excel

    Related course: Data Analysis with Python Pandas

    If you do not need to write index (row name), columns (column name), the argument index, columns is False.

    1
    df.to_excel('pandas_to_excel_no_index_header.xlsx', index=False, header=False)

    Write multiple DataFrames to Excel files

    The ExcelWriter object allows you to use multiple pandas. DataFrame objects can be exported to separate sheets.

    As an example, pandas. Prepare another DataFrame object.

    1
    2
    3
    4
    5
    6
    df2 = df[['a', 'c']]
    print(df2)




    Then use the ExcelWriter() function like this:

    1
    2
    3
    with pd.ExcelWriter('pandas_to_excel.xlsx') as writer:
    df.to_excel(writer, sheet_name='sheet1')
    df2.to_excel(writer, sheet_name='sheet2')

    You don’t need to call writer.save(), writer.close() within the blocks.

    Append to an existing Excel file

    You can append a DataFrame to an existing Excel file. The code below opens an existing file, then adds two sheets with the data of the dataframes.

    Note: Because it is processed using openpyxl, only .xlsx files are included.

    1
    2
    3
    4
    5
    6
    path = 'pandas_to_excel.xlsx'

    with pd.ExcelWriter(path) as writer:
    writer.book = openpyxl.load_workbook(path)
    df.to_excel(writer, sheet_name='new_sheet1')
    df2.to_excel(writer, sheet_name='new_sheet2')

    Related course: Data Analysis with Python Pandas

    Понравилась статья? Поделить с друзьями:
  • Pandas dataframe to excel file
  • Pandas dataframe save to excel
  • Pandas dataframe export excel
  • Pandas create excel file
  • Pandas add sheet to excel