Python pandas export 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() можно найти здесь .

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

    Excel files can be a great way of saving your tabular data particularly when you want to display it (and even perform some formatting to it) in a nice GUI like Microsoft Excel. In this tutorial, we’ll look at how to save a pandas dataframe to an excel .xlsx file.

    Note: The terms “excel file” and “excel workbook” are used interchangeably in this tutorial.

    The to_excel() function

    The pandas DataFrame to_excel() function is used to save a pandas dataframe to an excel file. It’s like the to_csv() function but instead of a CSV, it writes the dataframe to a .xlsx file. The following is its syntax:

    df.to_excel("pathfile_name.xlsx")

    Here, df is a pandas dataframe and is written to the excel file file_name.xlsx present at the location path. By default, the dataframe is written to Sheet1 but you can also give custom sheet names. You can also write to multiple sheets in the same excel workbook as well (See the examples below).

    Note that once the excel workbook is saved, you cannot write further data without rewriting the whole workbook.

    Examples

    First, we’ll create a sample dataframe that we’ll be using throughout this tutorial.

    import pandas as pd
    
    data = {
        'Name': ['Microsoft Corporation', 'Google, LLC', 'Tesla, Inc.',
                 'Apple Inc.', 'Netflix, Inc.'],
        'Symbol': ['MSFT', 'GOOG', 'TSLA', 'AAPL', 'NFLX'],
        'Shares': [100, 50, 150, 200, 80]
    }
    
    # create dataframe from data
    df = pd.DataFrame(data)
    # display the dataframe
    df

    pandas dataframe containing information on a stock portfolio

    Now, let’s look at examples of some of the different use-cases where the to_excel() function might be useful.

    1. Save dataframe to an excel file with default parameters

    df.to_excel("portfolio.xlsx")

    If you just pass the file name to the to_excel() function and use the default values for all the other parameters, the resulting Excel file gets saved in your current working directory with the given file name. Here’s a snapshot of the file when opened in Excel.

    Snapshot of the excel file saved

    You can see that by default, the dataframe is saved to the sheet Sheet1. Also, note that the index of the dataframe is saved as a separate column. Pass index=False if you don’t want the index as a separate column in the excel file.

    # to not include index as a column
    df.to_excel("portfolio.xlsx", index=False)

    Here’s how the saved excel file looks now.

    Snapshot of the saved pandas dataframe without index in excel.

    2. Save dataframe to an excel file with custom sheet name

    You can specify the name of the worksheet using the sheet_name parameter.

    # with custom sheet name
    df.to_excel("portfolio.xlsx", sheet_name="stocks")

    Snapshot of the saved dataframe with custom worksheet name

    You can see in the above snapshot that the resulting excel file has stocks as its sheet name.

    3. Save to multiple sheets in the same workbook

    You can also save dataframes to multiple worksheets within the same workbook using the to_excel() function. For this, you need to specify an ExcelWriter object which is a pandas object used to write to excel files. See the example below:

    # write to multiple sheets
    df2 = df.copy()
    with pd.ExcelWriter("portfolio.xlsx") as writer:
        df.to_excel(writer, sheet_name="stocks1")
        df2.to_excel(writer, sheet_name="stocks2")

    Here’s how the saved excel file looks.

    Snapshot of excel file with dataframes saved to two worksheets

    In the above example, an ExcelWriter object is used to write the dataframes df and df2 to the worksheets stocks1 and stocks2 respectively.

    Note that creating an ExcelWriter object with a file name that already exists will result in the contents of the existing file being erased.

    For more on the pandas dataframe to_excel() function, refer to its official documentation.

    You might also be interested in –

    • Write a Pandas DataFrame to a JSON File
    • Copy Pandas DataFrame to the Clipboard
    • Save Pandas DataFrame to a CSV file

    With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5

    Subscribe to our newsletter for more informative guides and tutorials.
    We do not spam and you can opt out any time.

    • Piyush Raj

      Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

      View all posts

    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.


    Often you may be interested in exporting a pandas DataFrame to Excel. Fortunately this is easy to do using the pandas to_excel() function.

    In order to use this function, you’ll need to first install openpyxl so that you’re able to write files to Excel:

    pip install openpyxl

    This tutorial will explain several examples of how to use this function with the following DataFrame:

    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
    

    Example 1: Basic Export

    The following code shows how to export the DataFrame to a specific file path and save it as mydata.xlsx:

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

    Here’s what the actual Excel file looks like:

    Example 2: Export without Index

    The following code shows how to export the DataFrame to a specific file path and remove the index column:

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

    Here’s what the actual Excel file looks like:

    Example 3: Export without Index and Header

    The following code shows how to export the DataFrame to a specific file path and remove the index column and the header row:

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

    Here’s what the actual Excel file looks like:

    Example 4: Export and Name the Sheet

    The following code shows how to export the DataFrame to a specific file path and name the Excel worksheet:

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

    Here’s what the actual Excel file looks like:

    You can find the complete documentation for the to_excel() function here.

    Понравилась статья? Поделить с друзьями:
  • Python excel read and write
  • Python pandas excel форматирование
  • Python pandas excel пример
  • Python excel read all sheets
  • Python pandas excel листы