Excel export from pandas

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


    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.

    Понравилась статья? Поделить с друзьями:
  • Excel explorer что это за программа
  • Excel exit for vba excel
  • Excel exist in table
  • Excel exe что это такое
  • Excel exe точка входа не найдена