Запись DataFrames в файлы
Экспортируйте очищенный DataFrame в CSV и Excel с помощью to_csv и to_excel, настраивая индекс и формат чисел с плавающей точкой
«Запись DataFrames в файлы» — бесплатный урок Pandas & NumPy Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Pandas & NumPy Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Pandas & NumPy Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Export Matters
Data analysis rarely ends inside Python. You need to share cleaned datasets with stakeholders, feed results into other tools, or archive processed data for reproducibility. Pandas provides to_csv(), to_excel(), to_json(), and to_parquet() — mirroring the read functions and accepting most of the same configuration parameters.
import pandas as pd
df = pd.DataFrame({'name': ['A', 'B'], 'score': [90, 75]})
df.to_csv('results.csv')
df.to_excel('results.xlsx')
df.to_json('results.json', orient='records')to_csv(): The Index Gotcha
By default to_csv() writes the row index as the first column, creating an unnamed: 0 column when you read the file back. Pass index=False to omit the index — almost always the right choice unless the index itself is meaningful data (like dates). Always specify index=False unless you have a deliberate reason to include the index.
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
# Include index (default -- creates 'Unnamed: 0' when re-read)
df.to_csv('with_index.csv')
# Exclude index (recommended)
df.to_csv('clean.csv', index=False)Controlling Delimiter and Encoding
Pass sep= to write a tab-separated or semicolon-separated file. Use encoding= to specify UTF-8 or another character set — essential when column values contain non-ASCII characters like accents or Chinese characters. encoding='utf-8-sig' adds a BOM (byte-order mark) for Excel compatibility on Windows.
import pandas as pd
df = pd.DataFrame({'name': ['Müller', 'Tanaka'], 'val': [1, 2]})
# Tab-separated, UTF-8
df.to_csv('output.tsv', sep='\t', encoding='utf-8', index=False)
# Excel-compatible UTF-8 with BOM
df.to_csv('for_excel.csv', encoding='utf-8-sig', index=False)Controlling Float Formatting
By default Pandas writes floats with full precision. Use float_format='%.2f' to limit to 2 decimal places — important for financial data where extra decimal places look wrong to human readers. Pass na_rep='NULL' or na_rep='' to control how NaN values are written in the output file.
import pandas as pd
import numpy as np
df = pd.DataFrame({'price': [9.99, np.nan, 14.123456],
'qty': [1, 2, 3]})
df.to_csv('prices.csv',
index=False,
float_format='%.2f',
na_rep='N/A')to_excel(): Writing a Sheet
df.to_excel('file.xlsx', sheet_name='Data', index=False) writes the DataFrame to an Excel workbook. Like to_csv(), set index=False unless the index is meaningful. The startrow= and startcol= parameters let you position the table within the sheet — useful for adding a title row above the data.
import pandas as pd
df = pd.DataFrame({'product': ['A', 'B'], 'sales': [100, 200]})
df.to_excel('report.xlsx',
sheet_name='Sales',
index=False,
startrow=1) # leave row 0 for a titleWriting Multiple Sheets with ExcelWriter
To write multiple DataFrames to different sheets in the same workbook, use pd.ExcelWriter as a context manager. Call df.to_excel(writer, sheet_name='Name') for each DataFrame inside the with block. The workbook is finalised and saved when the context exits. This avoids creating multiple separate files for related tables.
import pandas as pd
df1 = pd.DataFrame({'a': [1, 2]})
df2 = pd.DataFrame({'b': [3, 4]})
with pd.ExcelWriter('multi_sheet.xlsx', engine='openpyxl') as writer:
df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet2', index=False)to_json(): Exporting JSON
df.to_json() serialises a DataFrame to JSON. The orient= parameter mirrors read_json: use 'records' for a list of row dicts (most interoperable), 'columns' for a dict of column arrays, or 'index' for a dict keyed by row label. Pass indent=2 for human-readable formatting.
import pandas as pd
df = pd.DataFrame({'name': ['A', 'B'], 'score': [90, 75]})
print(df.to_json(orient='records', indent=2))
# [
# {"name": "A", "score": 90},
# {"name": "B", "score": 75}
# ]Appending to an Existing File
To append rows to an existing CSV without overwriting, open the file in append mode using mode='a' and set header=False to avoid duplicating the header row. For Excel, use ExcelWriter with mode='a'. For large streaming pipelines, append in chunks and write the header only on the first chunk.
import pandas as pd
df_new = pd.DataFrame({'a': [5, 6], 'b': [7, 8]})
# Append to existing file, skip writing header
df_new.to_csv('existing.csv',
mode='a',
header=False,
index=False)Selecting Columns Before Export
A good practice before exporting is to select only the columns the recipient needs and to sort rows in a logical order. This makes the output file cleaner and prevents accidentally leaking internal columns like internal IDs, encoded features, or debug flags. Use bracket selection and sort_values() in the same pipeline expression before writing.
import pandas as pd
df = pd.DataFrame({'id': [3,1,2],
'name': ['C','A','B'],
'_internal': [9,7,8]})
(df[['id', 'name']]
.sort_values('id')
.to_csv('export.csv', index=False))Verifying the Written File
After writing, always read the file back and verify: check shape, column names, and a few spot values. For CI pipelines, compare checksums. For critical financial exports, assert that aggregated totals match. This catches encoding issues, float precision loss, and index problems before the file reaches a downstream consumer.
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
df.to_csv('/tmp/check.csv', index=False)
df_check = pd.read_csv('/tmp/check.csv')
assert df_check.shape == df.shape, 'Row/column count mismatch'
assert list(df_check.columns) == list(df.columns)
print('Export verified OK')Parquet: A Better Alternative for Data
For large analytical datasets, consider Parquet format instead of CSV. Parquet stores data in columnar format, supports compression, preserves dtypes exactly, and reads 10-100x faster for analytical queries. Write with df.to_parquet('data.parquet') and read with pd.read_parquet('data.parquet'). It requires pyarrow or fastparquet to be installed.
import pandas as pd
df = pd.DataFrame({'a': range(1000000), 'b': range(1000000)})
df.to_parquet('data.parquet', index=False)
df2 = pd.read_parquet('data.parquet')
print(df2.dtypes) # dtypes preserved exactlyQuick Check
Test your understanding of writing DataFrames to files from this lesson.
Lesson Recap
In this lesson you learned: to_csv() and to_excel() export DataFrames and both default to including the index — always set index=False for clean output, ExcelWriter enables writing multiple DataFrames to separate sheets in one workbook, and Parquet is a faster and more space-efficient alternative to CSV for large analytical datasets. Next up we load remote CSV files from URLs and parse in-memory CSV strings with io.StringIO.
Часто задаваемые вопросы
Урок «Запись DataFrames в файлы» бесплатный?
Да — полный текст урока «Запись DataFrames в файлы» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Pandas & NumPy Academy, подпишись на CoddyKit PRO. Курс Pandas & NumPy Academy содержит 4 уроков всего.
Чему я научусь в уроке «Запись DataFrames в файлы»?
Экспортируйте очищенный DataFrame в CSV и Excel с помощью to_csv и to_excel, настраивая индекс и формат чисел с плавающей точкой Ты практикуешь Pandas & NumPy Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Pandas & NumPy Academy?
Предыдущий опыт не требуется. Pandas & NumPy Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Запись DataFrames в файлы»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Pandas & NumPy Academy?
Да. Каждый урок Pandas & NumPy Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Чтение CSV-файлов
- Чтение файлов Excel и JSON
- Запись DataFrames в файлы
- Чтение из URL и StringIO