Dataframe экспортировать в 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

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

    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.


    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.

    Понравилась статья? Поделить с друзьями:
  • Dataframe to excel without index
  • Dataformat error входные данные не удалось распознать как допустимый документ excel сведения binary
  • Database to word document
  • Database to use with excel
  • Database in excel format