Как экспортировать фрейм данных Pandas в Excel
Часто вас может заинтересовать экспорт фрейма данных pandas в Excel. К счастью, это легко сделать с помощью функции pandas to_excel() .
Чтобы использовать эту функцию, вам нужно сначала установить openpyxl , чтобы вы могли записывать файлы в Excel:
pip install openpyxl
В этом руководстве будет объяснено несколько примеров использования этой функции со следующим фреймом данных:
import pandas as pd #create DataFrame df = pd.DataFrame() #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:\Users\Zach\Desktop\mydata.xlsx')
Вот как выглядит фактический файл Excel:

Пример 2: Экспорт без индекса
В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и удалить столбец индекса:
df.to_excel (r'C:\Users\Zach\Desktop\mydata.xlsx', index= False )
Вот как выглядит фактический файл Excel:

Пример 3: Экспорт без индекса и заголовка
В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и удалить столбец индекса и строку заголовка:
df.to_excel (r'C:\Users\Zach\Desktop\mydata.xlsx', index= False, header= False )
Вот как выглядит фактический файл Excel:

Пример 4: Экспорт и имя листа
В следующем коде показано, как экспортировать DataFrame в определенный путь к файлу и назвать рабочий лист Excel:
df.to_excel (r'C:\Users\Zach\Desktop\mydata.xlsx', sheet_name='this_data')
Вот как выглядит фактический файл Excel:

Полную документацию по функции to_excel() можно найти здесь .
Python.Pandas. Как записать в excel
Как записать все данные из цикла? А то при использовании met_skv_3.to_excel(‘metki1.xlsx’,sheet_name=’er’) в файл записываются последние элементы цикла: 
Отслеживать
149k 12 12 золотых знаков 59 59 серебряных знаков 132 132 бронзовых знака
задан 19 окт 2016 в 8:55
Рамиль Фазлиахметов Рамиль Фазлиахметов
25 1 1 золотой знак 1 1 серебряный знак 6 6 бронзовых знаков
по-моему проще будет объединить все DataFrame’s в один и записать этот объединённый DF в Excel
19 окт 2016 в 9:50
Еще я бы не перечитывал Excel в цыкле — можно просто выбирать нужный диапазон столбцов из tab DF. Если выложите куда-нибудь свой Excel файл я мог бы набросать рабочий вариант.
19 окт 2016 в 9:58
@MaxU dropmefiles.com/KJfVT вот файл.
19 окт 2016 в 10:13
@MaxU дело в том, что задача стоит так, что данных диапазонов может быть и не 19 штук, как у меня, а может и больше. Кроме как цикла не имею понятия как делать, и желательно чтобы данные каждого из диапазонов выводились также, как и в исходном файле
19 окт 2016 в 11:11
Результат вы хотите записать в вертикальном виде (т.е. блоки по пять столбцов один под другим) — я вас правильно понимаю?
19 окт 2016 в 11:50
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
Вот рабочий вариант, который читает Excel файл только один раз:
import pandas as pd fn = r'C:\Temp\.data\primer.xlsx' cols = ['label','x','y','z','value'] df = pd.read_excel(fn, skiprows=4, header=None, parse_cols='C:XFD') dfs = [] for i in range(df.columns.size//5): lbl_col = 5*i x = df.ix[(df[lbl_col] != 0) & (df[lbl_col] != 9999), lbl_col:lbl_col+4] #x.columns = pd.MultiIndex.from_tuples(list(product([i+1], cols))) x.columns = cols dfs.append(x.reset_index(drop=True)) result = pd.concat(dfs, axis=1) #result.to_excel('c:/temp/result.xlsx', startrow=3, index=True) result.to_excel('c:/temp/result.xlsx', startrow=3, index=False)

PS я хотел добавить номера пяти-столбцовых блоков (как в вашем исходном файле: 1-19), т.е. создать multilevel columns :
x.columns = pd.MultiIndex.from_tuples(list(product([i+1], cols)))
но это пока не имплементировано:
NotImplementedError: Writing to Excel with MultiIndex columns and no index ('index'=False) is not yet implemented.
Т.е. надо выбирать — либо многоуровневые (красивые) имена столбцов и ненужный индекс, либо нет индекса и одноуровневые имена столбцов.
PPS если нужна «шапка», то сделать это можно подобным образом
Как записать несколько DataFrame в мультистраничную книгу .xlsx используя xlsxwriter?
Стоит задача, спарсить (с парсингом проблем нет) несколько однообразных страничек и записать полученные данные в таблицу, причём во время парсинга каждой из страничек мы должны создать словарь, из него DataFrame, и этот DataFrame записать в отдельный лист в .xlsx книге, после чего операция повторяется. Если нужно обработать лишь одну страничку всё нормально. Но если их несколько, возникает одна проблема: новые листы не создаются. Вместо этого, DataFrame записываются в один и тот же лист (также странно, что в конечном файле остаётся не последний DataFrame, а ВСЕ DataFrame, несмотря на то, что xlsxwriter режим append не поддерживает и в теории должен делать перезапись), и этот лист имеет название последней итерируемой странички. Скорее всего это происходит, потому что используется один и тот же DataFrame (под именем database ), имя которого не меняется и он просто обнуляется при анализе новой страницы, но я не уверен — если создать его копию, она по-прежнему записывается в один и тот же лист (хотя это может быть из-за того что я оставлял ссылку на один и тот же DataFrame, пытаясь оставить копию). Вряд ли xlsxwriter сохраняет по принципу «Сохранять в один и тот же лист, если имя DataFrame не меняется» Код:
from bs4 import BeautifulSoup from pandas import ExcelWriter import pandas as pd import os import xlsxwriter def nametreat(txt): # Это функции для обработки текста if txt[-1] == ')': bracktxt = '' i = 1 while txt[-i] != '(': bracktxt += txt[-i] i += 1 bracktxt = bracktxt[::-1] if 'класс' in bracktxt: while txt[-1] != '(': txt = txt[0:-1:1] return txt[0:-2:1] else: return txt def spaceclear(txt): # Это функция для обработки текста while len(txt) > 0 and (txt[0] == ' ' or txt[0] == '\n'): txt = txt[1:] while len(txt) > 0 and (txt[-1] == ' ' or txt[-1] == '\n'): txt = txt[0:-1] return txt def courseinfo(bs): clss_, times, month = bs.find_all('div', attrs = ) clss_, times, month = map(spaceclear, [clss_.text, times.text, month.text]) nums = '0123456789' while clss_[-1] not in nums: clss_ = clss_[0:-1:1] if '-' not in clss_: start = int(clss_) end = start else: start, end = map(int, clss_.split('-')) clss_ = list(range(start, end + 1)) while times[-1] not in nums: times = times[0:-1:1] times = [int(times[0]), int(times[-1])] month = list(month.split('-')) res = [clss_, times, month] return res science = open('schools_science.html', encoding = 'utf-8', mode = 'r') sport = open('schools_sport.html', encoding = 'utf-8', mode = 'r') creative = open('schools_creative.html', encoding = 'utf-8', mode = 'r') teaming = open('schools_teaming.html', encoding = 'utf-8', mode = 'r') responsib = open('schools_responsib.html', encoding = 'utf-8', mode = 'r') files = [science, sport, teaming, creative, responsib] maindict = < 'name': [], 'type': [], 'description': [], 'text': [], 'grades': [], 'times_a_week': [], 'lessons': [], 'from_month': [], 'to_month': [] >database = pd.DataFrame(maindict) tablist = ['Science', 'Sport', 'Creative', 'Teaming', 'Responsibility'] tab = 0 for file in files: soup = BeautifulSoup(file, 'lxml') courses = soup.find_all("div", attrs = ) for cl in courses: maindict['type'].append(spaceclear(cl.find("div", attrs = ).text)) maindict['name'].append(nametreat(spaceclear(cl.find("h2").text))) maindict['description'].append(spaceclear(cl.find("div", attrs = ).text)) maindict['text'].append(spaceclear(cl.find("div", attrs = ).find("p").text)) clss_, times, month = map(spaceclear, courseinfo(cl)) maindict['grades'].append(clss_) maindict['times_a_week'].append(times[0]) maindict['lessons'].append(times[1]) maindict['from_month'].append(month[0]) maindict['to_month'].append(month[1]) database = pd.DataFrame(maindict) with ExcelWriter(path = 'schools.xlsx', engine = 'xlsxwriter') as writer: database.to_excel(writer, sheet_name = tablist[tab], index = False) writer.save() tab += 1 exit(0)
pandas.DataFrame.to_excel#
DataFrame. to_excel ( excel_writer , sheet_name = ‘Sheet1’ , na_rep = » , float_format = None , columns = None , header = True , index = True , index_label = None , startrow = 0 , startcol = 0 , engine = None , merge_cells = True , inf_rep = ‘inf’ , freeze_panes = None , storage_options = None , engine_kwargs = None ) [source] #
Write object to an Excel sheet.
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.
engine_kwargs dict, optional
Arbitrary keyword arguments passed to excel engine.
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:
>>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']], . index=['row 1', 'row 2'], . columns=['col 1', 'col 2']) >>> df1.to_excel("output.xlsx")
To specify the sheet name:
>>> df1.to_excel("output.xlsx", . sheet_name='Sheet_name_1')
If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object:
>>> df2 = df1.copy() >>> with pd.ExcelWriter('output.xlsx') as writer: . df1.to_excel(writer, sheet_name='Sheet_name_1') . df2.to_excel(writer, sheet_name='Sheet_name_2')
ExcelWriter can also be used to append to an existing Excel file:
>>> with pd.ExcelWriter('output.xlsx', . mode='a') as writer: . df1.to_excel(writer, sheet_name='Sheet_name_3')
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):
>>> df1.to_excel('output1.xlsx', engine='xlsxwriter')
