JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Pandas DataFrame DataFrame.to_csv() function

Author:JIYIK Last Updated:2025/04/30 Views:

Python Pandas DataFrame.to_csv() function DataFramesaves the values ​​contained in the rows and columns of a to a CSV file. We can also DataFrameconvert to a CSV string.


pandas.DataFrame.to_csv()grammar

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=".",
)

parameter

This function has several parameters. The default values ​​for all the parameters are mentioned above.

path_or_buf It is a string or a file handle. It represents the name of a file or a file object. If its value is None, then it DataFramewill be converted to a CSV "string".
sep It is a Seriesstring that represents the delimiter used in the CSV file.
na_rep It is a string. It represents the missing data.
float_format It is a string. It represents the format of the floating point number.
columns It is a Series. It represents the columns that will be saved in the CSV file DataFrame.
header It is a boolean value or a list of strings. If its value is set to False, then the column names will not be saved in the CSV file. If a list of strings is passed, then those strings will be saved as column names.
index It is a boolean value, if its value is True, then the row names i.e. index will be saved. If its value is True, then the row names i.e. index will be saved.
index_label It is a string or Series. It represents the column name of a specific index.
mode It is a string. It represents the mode of the process. Since we are DataFramewriting to a CSV file, its value is the Python write mode w.
encoding It is a string. It represents the encoding scheme to be used in the CSV file. The default encoding scheme is utf-8. The default encoding scheme is utf-8.
compression It is a string or a dictionary. If it is a string, it represents the compression mode. If it is a dictionary, then methodthe value corresponding to the key represents the compression mode. It has several compression modes. You can check it here .
quoting It represents a constant of the CSV module
quotechar It is a string, of length 1. It has a length of 1 and represents the character used to quote the field.
line_terminator It is a string that represents the characters for new lines in the CSV file.
chunksize It is an integer. It represents the number of rows to be written to the CSV file each time.
date_format It is a string. It represents DateTimethe format of the object.
doublequote It is a Boolean value. It controls quotecharthe reference of .
escapechar It is a string of length 1. Its length is 1 and represents the characters used for escaping sepand quotechar.
decimal It is a string. It represents the character of the decimal point.

Return Value

It returns Noneeither or a string. If path_or_bufis Nonethen it DataFrameconverts to a string and returns the string. Otherwise, it returns None.


Sample code:DataFrame.to_csv()

In the next few code snippets, we will implement this function in different ways.

import pandas as pd

dataframe=pd.DataFrame({
                        'Attendance': 
                            {0: 60, 
                            1: 100, 
                            2: 80,
                            3: 78,
                            4: 95},
                        'Name': 
                            {0: 'Olivia', 
                            1: 'John', 
                            2: 'Laura',
                            3: 'Ben',
                            4: 'Kevin'},
                        'Obtained Marks': 
                            {0: 90, 
                            1: 75, 
                            2: 82, 
                            3: 64, 
                            4: 45}
                        })

print(dataframe)

Examples DataFrameare:

   Attendance    Name  Obtained Marks
0          60  Olivia              90
1         100    John              75
2          80   Laura              82
3          78     Ben              64
4          95   Kevin              45

All the parameters of this function are optional. If we do not pass any parameters while executing this function, then it will produce the following output.

import pandas as pd

dataframe = pd.DataFrame(
    {
        "Attendance": {0: 60, 1: 100, 2: 80, 3: 78, 4: 95},
        "Name": {0: "Olivia", 1: "John", 2: "Laura", 3: "Ben", 4: "Kevin"},
        "Obtained Marks": {0: 90, 1: 75, 2: 82, 3: 64, 4: 45},
    }
)

csvstring = dataframe.to_csv()
print(csvstring)

Output:

,Attendance,Name,Obtained Marks
0,60,Olivia,90
1,100,John,75
2,80,Laura,82
3,78,Ben,64
4,95,Kevin,45

The function generated the output using all the default values. It returned a CSV string. Now we will save the data in a CSV file.

import pandas as pd

dataframe = pd.DataFrame(
    {
        "Attendance": {0: 60, 1: 100, 2: 80, 3: 78, 4: 95},
        "Name": {0: "Olivia", 1: "John", 2: "Laura", 3: "Ben", 4: "Kevin"},
        "Obtained Marks": {0: 90, 1: 75, 2: 82, 3: 64, 4: 45},
    }
)

returnValue = dataframe.to_csv("myfile.csv")
print(returnValue)

Output:

None

The function creates a new CSV file in the directory where the program is saved.


Sample code: DataFrame.to_csv()Specifying delimiters for CSV data

import pandas as pd

dataframe = pd.DataFrame(
    {
        "Attendance": {0: 60, 1: 100, 2: 80, 3: 78, 4: 95},
        "Name": {0: "Olivia", 1: "John", 2: "Laura", 3: "Ben", 4: "Kevin"},
        "Obtained Marks": {0: 90, 1: 75, 2: 82, 3: 64, 4: 45},
    }
)

returnValue = dataframe.to_csv(sep="@")
print(returnValue)

Output:

@Attendance@Name@Obtained Marks

0@60@Olivia@90

1@100@John@75

2@80@Laura@82

3@78@Ben@64

4@95@Kevin@45

Sample code: DataFrame.to_csv()Select a few columns and rename the columns

import pandas as pd

dataframe = pd.DataFrame(
    {
        "Attendance": {0: 60, 1: 100, 2: 80, 3: 78, 4: 95},
        "Name": {0: "Olivia", 1: "John", 2: "Laura", 3: "Ben", 4: "Kevin"},
        "Obtained Marks": {0: 90, 1: 75, 2: 82, 3: 64, 4: 45},
    }
)

returnValue = dataframe.to_csv(
    "myfile.csv", columns=["Name", "Obtained Marks"], header=["Full Name", "Marks"]
)
print(returnValue)

Output:

None

Just like the code above, we can use different parameters to customize our CSV file. This function provides several parameters to use.

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.

Article URL:

Related Articles

Pandas DataFrame DataFrame.query() function

Publish Date:2025/04/30 Views:107 Category:Python

The pandas.DataFrame.query() method filters the rows of the caller DataFrame using the given query expression. pandas.DataFrame.query() grammar DataFrame . query(expr, inplace = False , ** kwargs) parameter expr Filter rows based on query e

Pandas DataFrame DataFrame.min() function

Publish Date:2025/04/30 Views:162 Category:Python

Python Pandas DataFrame.min() function gets the minimum value of the DataFrame object along the specified axis. pandas.DataFrame.min() grammar DataFrame . mean(axis = None , skipna = None , level = None , numeric_only = None , ** kwargs) pa

Pandas DataFrame DataFrame.mean() function

Publish Date:2025/04/30 Views:85 Category:Python

Python Pandas DataFrame.mean() function calculates the mean of the values ​​of the DataFrame object over the specified axis. pandas.DataFrame.mean() grammar DataFrame . mean(axis = None , skipna = None , level = None , numeric_only = No

Pandas DataFrame DataFrame.isin() function

Publish Date:2025/04/30 Views:133 Category:Python

The pandas.DataFrame.isin(values) function checks whether each element in the caller DataFrame contains values the value specified in the input . pandas.DataFrame.isin(values) grammar DataFrame . isin(values) parameter values iterable - lis

Pandas DataFrame DataFrame.groupby() function

Publish Date:2025/04/30 Views:161 Category:Python

pandas.DataFrame.groupby() takes a DataFrame as input and divides the DataFrame into groups based on a given criterion. We can use groupby() the method to easily process large datasets. pandas.DataFrame.groupby() grammar DataFrame . groupby

Pandas DataFrame DataFrame.fillna() function

Publish Date:2025/04/30 Views:60 Category:Python

The pandas.DataFrame.fillna() function replaces the values DataFrame ​​in NaN with a certain value. pandas.DataFrame.fillna() grammar DataFrame . fillna( value = None , method = None , axis = None , inplace = False , limit = None , down

Pandas DataFrame DataFrame.dropna() function

Publish Date:2025/04/30 Views:181 Category:Python

The pandas.DataFrame.dropna() function removes null values ​​(missing values) from a DataFrame by dropping rows or columns that contain null values DataFrame . NaN ( Not a Number ) and NaT ( Not a Time ) represent null values. DataFrame

Pandas DataFrame DataFrame.assign() function

Publish Date:2025/04/30 Views:55 Category:Python

Python Pandas DataFrame.assign() function assigns new columns to DataFrame . pandas.DataFrame.assign() grammar DataFrame . assign( ** kwargs) parameter **kwargs Keyword arguments, DataFrame the column names to be assigned to are passed as k

Pandas DataFrame DataFrame.transform() function

Publish Date:2025/04/30 Views:120 Category:Python

Python Pandas DataFrame.transform() DataFrame applies a function on and transforms DataFrame . The function to be applied is passed as an argument to the function. The axis length of transform() the transformed should be the same as the ori

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial