DataFrame to CSV - ( Pandas Operations )
Heading h2
Syntax
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='.')
Example
import pandas as pd
# creating a sample dataframe
data = {'Name': ['John', 'Anna', 'Peter', 'Linda'], 'Age': [25, 32, 18, 41]}
df = pd.DataFrame(data)
# writing dataframe to a CSV file
df.to_csv('sample.csv', index=False)
Output
The above code will create a CSV file named sample.csv
containing the data from the DataFrame
.
Name,Age
John,25
Anna,32
Peter,18
Linda,41
Explanation
DataFrame.to_csv()
is a pandas function that writes the data from a DataFrame to a CSV file. It takes in several parameters such as file path, separator, header, index, and more to customize the output.
In the above example, we create a sample DataFrame and then write the data from the DataFrame to a CSV file named sample.csv
. We use the index=False
parameter to exclude the row index from the output file.
Use
DataFrame.to_csv()
is a useful function in pandas that allows us to write data from a DataFrame to a CSV file. This function can be used in various data processing and analysis tasks such as data cleaning, data transformation, and data visualizations.
Important Points
DataFrame.to_csv()
writes the data from a DataFrame to a CSV file- It takes in several parameters such as file path, separator, header, index, and more to customize the output
- The default separator is a comma (
,
) and the default decimal is.
Summary
In conclusion, DataFrame.to_csv()
is a useful pandas function for writing data from a DataFrame to a CSV file. It provides various customization options such as file path, separator, header, index, and more. This function is widely used in data processing and analysis tasks in data science and machine learning.