Writing a Pandas DataFrame to CSV
This tutorial explains how we can use pandas.DataFrame.to_csv()
the function to write a DataFrame to a CSV file. pandas.DataFrame.to_csv()
The function writes the elements of a DataFrame to a CSV file.
pandas.DataFrame.to_csv()
Function syntax
pandas.DataFrame.to_csv(
path_or_buf=None,
sep=",",
na_rep="",
float_format=None,
columns=None,
header=True,
index=True,
index_label=None,
mode="w",
encoding=None,
compression="infer",
quoting=None,
quotechar='""',
line_terminator=None,
chunksize=None,
date_format=None,
doublequote=True,
escapechar=None,
decimal=".",
)
Use pandas.DataFrame.to_csv()
the function to write the DataFrame to a CSV file
import pandas as pd
mid_term_marks = {
"Student": ["Kamal", "Arun", "David", "Thomas", "Steven"],
"Economics": [10, 8, 6, 5, 8],
"Fine Arts": [7, 8, 5, 9, 6],
"Mathematics": [7, 3, 5, 8, 5],
}
mid_term_marks_df = pd.DataFrame(mid_term_marks)
print(mid_term_marks_df)
Output:
Student Economics Fine Arts Mathematics
0 Kamal 10 7 7
1 Arun 8 8 3
2 David 6 5 5
3 Thomas 5 9 8
4 Steven 8 6 5
We will then mid_term_marks_df
write the DataFrame to a CSV file.
import pandas as pd
mid_term_marks = {
"Student": ["Kamal", "Arun", "David", "Thomas", "Steven"],
"Economics": [10, 8, 6, 5, 8],
"Fine Arts": [7, 8, 5, 9, 6],
"Mathematics": [7, 3, 5, 8, 5],
}
mid_term_marks_df = pd.DataFrame(mid_term_marks)
mid_term_marks_df.to_csv("midterm.csv")
It will create a midterm.csv
file named and write the values of the DataFrame to that file, with adjacent rows of values ,
separated by commas .
midterm.csv
The content of the file will be.
,Student,Economics,Fine Arts,Mathematics
0,Kamal,10,7,7
1,Arun,8,8,3
2,David,6,5,5
3,Thomas,5,9,8
4,Steven,8,6,5
By default, pandas.DataFrame.to_csv()
the function will also write the DataFrame's index to the CSV, but the index may not always be useful in all cases.
Use pandas.DataFrame.to_csv()
the function to write a DataFrame to a CSV file and ignore the index
To ignore the index, we can pandas.DataFrame.to_csv()
set it in the function index=False
.
import pandas as pd
mid_term_marks = {
"Student": ["Kamal", "Arun", "David", "Thomas", "Steven"],
"Economics": [10, 8, 6, 5, 8],
"Fine Arts": [7, 8, 5, 9, 6],
"Mathematics": [7, 3, 5, 8, 5],
}
mid_term_marks_df = pd.DataFrame(mid_term_marks)
mid_term_marks_df.to_csv("midterm.csv", index=False)
In this case midterm.csv
the contents of the file will be.
Student,Economics,Fine Arts,Mathematics
Kamal,10,7,7
Arun,8,8,3
David,6,5,5
Thomas,5,9,8
Steven,8,6,5
Sometimes, when we write the contents of a DataFrame to a CSV file, this may happen UnicodeEncodeError
. In this case, we can set encoding='utf-8'
and enable utf-8
the encoding format.
pandas.DataFrame.to_csv()
Specify a delimiter in the function
By default, when writing a DataFrame to a CSV file, the values are separated by commas. If we want to use a different separator, we can sep
specify it using the comma separator parameter.
import pandas as pd
mid_term_marks = {
"Student": ["Kamal", "Arun", "David", "Thomas", "Steven"],
"Economics": [10, 8, 6, 5, 8],
"Fine Arts": [7, 8, 5, 9, 6],
"Mathematics": [7, 3, 5, 8, 5],
}
mid_term_marks_df = pd.DataFrame(mid_term_marks)
mid_term_marks_df.to_csv("midterm.csv", index=False, sep="\t")
In this case midterm.csv
the contents of the file will be.
Student Economics Fine Arts Mathematics
Kamal 10 7 7
Arun 8 8 3
David 6 5 5
Thomas 5 9 8
Steven 8 6 5
Here the values are separated by tabs.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to Convert DataFrame Column to String in Pandas
Publish Date:2025/05/02 Views:161 Category:Python
-
We will look at methods for converting Pandas DataFrame columns to strings. Pandas Series.astype(str) Method DataFrame.apply() Methods operate on the elements in a column We will use the same DataFrame below in this article. import pandas a
How to count the frequency of values in a Pandas DataFrame
Publish Date:2025/05/02 Views:84 Category:Python
-
Sometimes, when you use DataFrame , you may want to count the number of times a value occurs in a column, or in other words, calculate the frequency. There are mainly three methods used for this. Let's look at them one by one. df.groupby().
How to get value from Pandas DataFrame cell
Publish Date:2025/05/02 Views:147 Category:Python
-
We'll look at using to get values from cells in iloc Pandas , which is great for selecting by position, and how it differs from . We'll also learn about the and methods, which we can use when we don't want to set the return type to .
How to Add a Row to a Pandas DataFrame
Publish Date:2025/05/02 Views:127 Category:Python
-
Pandas is designed to load a fully populated DataFrame . We can pandas.DataFrame add them one by one in . This can be done by using various methods, such as .loc , dictionary, pandas.concat() or DataFrame.append() . .loc [index] Add rows to
How to change the order of Panas DataFrame columns
Publish Date:2025/05/02 Views:184 Category:Python
-
We will show how to use insert and reindex to change the order of columns in different ways pandas.DataFrame , such as assigning column names in a desired order. pandas.DataFrame Sort the columns in the new order The easiest way is columns
How to pretty print an entire Pandas Series/DataFrame
Publish Date:2025/05/02 Views:167 Category:Python
-
We will introduce various methods to pretty print the entire Pandas Series/DataFrame, such as option_context, set_option, and options.display. option_context Pretty Printing Pandas DataFrame We can option_context use with one or more option
How to count the number of NaN occurrences in a Pandas Dataframe column
Publish Date:2025/05/02 Views:144 Category:Python
-
We will look at methods for counting the number of NaN occurrences in a column of a Pandas DataFrame. We have a number of options, including isna() the method for one or more columns, by NaN subtracting the total length from the number of o
How to Convert a Pandas Dataframe to a NumPy Array
Publish Date:2025/05/02 Views:151 Category:Python
-
We will introduce to_numpy() the method to pandas.Dataframe convert a to NumPy an array, which is introduced in pandas v0.24.0, replacing the old .values method. We can define it on Index , Series , and DataFrame objects to_numpy . The old
How to add a header row to a Pandas DataFrame
Publish Date:2025/05/02 Views:161 Category:Python
-
We will look at methods for adding a header row to a pandas dataframe, as well as the option to pass in the names directly in the dataframe or by assigning the column names in a list directly to dataframe.columns the method. We will also in