DataFrames in Dateien schreiben
Exportieren Sie einen bereinigten DataFrame mit to_csv und to_excel nach CSV und Excel und steuern Sie dabei Index und Gleitkommaformat.
DataFrames in Dateien schreiben ist eine kostenlose Pandas & NumPy Academy-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Pandas & NumPy Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „DataFrames in Dateien schreiben“ kostenlos?
Ja — der vollständige Text von „DataFrames in Dateien schreiben“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Pandas & NumPy Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „DataFrames in Dateien schreiben“?
Exportieren Sie einen bereinigten DataFrame mit to_csv und to_excel nach CSV und Excel und steuern Sie dabei Index und Gleitkommaformat. Du übst Pandas & NumPy Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Pandas & NumPy Academy zu starten?
Keine Vorkenntnisse erforderlich. Pandas & NumPy Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.
Wie lange dauert die Lektion „DataFrames in Dateien schreiben“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Pandas & NumPy Academy-Lektion Code schreiben und ausführen?
Ja. Jede Pandas & NumPy Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- CSV-Dateien einlesen
- Excel- und JSON-Dateien einlesen
- DataFrames in Dateien schreiben
- Aus URLs und StringIO lesen