Как сохранить dataframe в excel python
Перейти к содержимому

Как сохранить dataframe в excel python

  • автор:

Как экспортировать фрейм данных Pandas в Excel

Как экспортировать фрейм данных Pandas в Excel

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pandas.DataFrame.to_excel#

To write a single object to an Excel .xlsx file it is only necessary to specify a target file name. To write to multiple sheets it is necessary to create an ExcelWriter object with a target file name, and specify a sheet in the file to write to.

Multiple sheets may be written to by specifying unique sheet_name . With all data written to the file it is necessary to save the changes. Note that creating an ExcelWriter object with a file name that already exists will result in the contents of the existing file being erased.

Parameters excel_writer path-like, file-like, or ExcelWriter object

File path or existing ExcelWriter.

sheet_name str, default ‘Sheet1’

Name of sheet which will contain DataFrame.

na_rep str, default ‘’

Missing data representation.

float_format str, optional

Format string for floating point numbers. For example float_format="%.2f" will format 0.1234 to 0.12.

columns sequence or list of str, optional

Columns to write.

header bool or list of str, default True

Write out the column names. If a list of string is given it is assumed to be aliases for the column names.

index bool, default True

Write row names (index).

index_label str or sequence, optional

Column label for index column(s) if desired. If not specified, and header and index are True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex.

startrow int, default 0

Upper left cell row to dump data frame.

startcol int, default 0

Upper left cell column to dump data frame.

engine str, optional

Write engine to use, ‘openpyxl’ or ‘xlsxwriter’. You can also set this via the options io.excel.xlsx.writer or io.excel.xlsm.writer .

merge_cells bool, default True

Write MultiIndex and Hierarchical Rows as merged cells.

inf_rep str, default ‘inf’

Representation for infinity (there is no native representation for infinity in Excel).

freeze_panes tuple of int (length 2), optional

Specifies the one-based bottommost row and rightmost column that is to be frozen.

storage_options dict, optional

Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to urllib.request.Request as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded to fsspec.open . Please see fsspec and urllib for more details, and for more examples on storage options refer here.

New in version 1.2.0.

Write DataFrame to a comma-separated values (csv) file.

Class for writing DataFrame objects into excel sheets.

Read an Excel file into a pandas DataFrame.

Read a comma-separated values (csv) file into DataFrame.

Add styles to Excel sheet.

For compatibility with to_csv() , to_excel serializes lists and dicts to strings before writing.

Once a workbook has been saved it is not possible to write further data without rewriting the whole workbook.

Create, write to and save a workbook:

To specify the sheet name:

If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object:

ExcelWriter can also be used to append to an existing Excel file:

To set the library that is used to write the Excel file, you can pass the engine keyword (the default engine is automatically chosen depending on the file extension):

Запись DataFrame Pandas в лист Excel

Вы можете сохранить или записать DataFrame в файл Excel или конкретный лист в файле Excel, используя метод pandas.DataFrame.to_excel() класса DataFrame.

В этом руководстве мы узнаем, как записать DataFrame Pandas в файл Excel с помощью примеров программ Python.

Необходимым условием для работы с функциями файлов Excel в pandas является установка модуля openpyxl. Чтобы установить openpyxl с помощью pip, выполните следующую команду.

Пример 1

  1. Подготовьте свой DataFrame. В этом примере мы инициализируем DataFrame с несколькими строками и столбцами.
  2. Создайте модуль записи Excel с именем выходного файла Excel, в который вы хотите записать наш DataFrame.
  3. Вызов функции to_excel() в DataFrame с помощью модуля записи Excel, переданного в качестве аргумента.
  4. Сохраните файл Excel, используя метод save() Excel Writer.

Запустите указанную выше программу, и файл Excel будет создан с именем, указанным при создании модуля записи Excel.

Выходной файл Excel

Откройте файл Excel, и вы увидите индекс, метки столбцов и данные строк, записанные в файл.

Запись DataFrame в лист Excel

Пример 2: запись на конкретный лист Excel

  1. Подготовьте свой DataFrame.
  2. Создайте модуль записи Excel с именем желаемого выходного файла Excel.
  3. Вызовите функцию to_excel() в DataFrame с записывающим устройством и именем листа Excel, переданными в качестве аргументов.
  4. Сохраните файл Excel, используя метод save() Excel Writer.

Выходной файл Excel

Откройте файл Excel. Обратите внимание на название листа Excel. Он назван в честь строки, которую мы указали в качестве второго аргумента функции to_excel().

Работа в листе Excel

В этом руководстве по Pandas мы узнали, как написать Pandas DataFrame в лист Excel с помощью примеров программ Python.

Introduction

Ankit songara

You might already be familiar with Pandas. Using Pandas, it is quite easy to export a data frame to an excel file. However, this exported file is very simple in terms of look and feel.

In this article we will try to make some changes in the formatting and try to make it more interesting visually.

For this job we will mostly use Pandas. And the data-set i’m going to use for this is some random credit card data. You can find the same here. I’m going to add some new columns to the following data-set for better understanding.

Let’s get started by importing pandas and numpy.

Reading the file:

“loc ”variable contains name of the folder where data-set file is present. You can directly put data-set file name along with the location in a single variable. I personally like concatenation. As you can see below, currently the file has 100 rows and 11 columns

Let’s add three more columns- “Balance”, “Credit Used” and “Credit Used Rate". For generating Balance we will use random.randint from numpy. For rest of the two columns, we can use simple math formulas.

If you notice, Credit Used Rate is in numbers but it should be in percentage format. We will change it afterwards. Now let’s save the above data frame to an excel file without changing any format. ExcelWriter is a class for writing Data-Frame into excel sheets. You can find more information about it here.

Let’s create another writer to save the formatted output file. Here we are using to_excel function for creating workbook

Now, let’s start the formatting. We will be making all the changes to the worksheet we created above.

Firstly, we will define the format variables, so that we can use them in the code where ever required. And, for this task we will use add_format.

Now, we will use above defined format variables in the worksheet using set_column.

Time to change header format. Zero in the below code implies 0th row which is basically the topmost row(Header Row).

lets show sum of certain numeric columns like “Balance”.

Saving the writer

The final output file would look like below file. You can see that format of some columns is changed. Header formatting is also differenct look different too

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *