Polars - Write DataFrame to CSV

Polars, a powerful DataFrame library, provides an easy way to write DataFrames to CSV files. Whether you’re saving your data for further analysis or sharing it with others, Polars makes the process straightforward. In this article, we’ll explore how to write a DataFrame to a CSV file using Polars.

Writing a DataFrame to CSV

To write a DataFrame to a CSV file, use the to_csv() method. Here’s how:

import polars as pl

# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 22]}
df = pl.DataFrame(data)

# Write the DataFrame to a CSV file
df.to_csv('my_data.csv')

print("DataFrame successfully written to my_data.csv")

By default, to_csv() writes the DataFrame with a header row containing column names. If you want to exclude the header, set header=False:

df.to_csv('my_data_no_header.csv', header=False)

Additional Options

Custom Separators: By default, Polars uses a comma (,) as the separator. You can specify a different separator using the sep argument:

df.to_csv('my_data_semicolon.csv', sep=';')

Index Column: By default, Polars includes an index column in the CSV file. To exclude it, set index=False:

df.to_csv('my_data_no_index.csv', index=False)

Null Values: Specify values to represent null (e.g., "NA", "null"):

df.to_csv('my_data_null.csv', na_rep='NA')

Conclusion

Polars simplifies CSV file handling with the to_csv() method. Whether you’re analyzing data or building machine learning models, Polars’ intuitive interface makes it a great choice for data manipulation.

Happy coding with Polars! 🚀📊


Publish Date: 2024-05-08, Update Date: 2024-05-08