Write Python Pandas Dataframe to CSV
In this article, you will learn how to convert a Python Pandas dataframe to a CSV.
After dealing with a dataset and performing all preprocessing, we must save the preprocessed information in a data format such as csv, excel, or others. CSV (Comma-separated-values) is widely used for data exchange in data-based applications. In web applications, we generally store the data in an array, dataframe, lists, tuples, dictionaries, etc. There may be a need for clients to export this data to a CSV file. The data in CSV is stored as sequences of records. Like in other programming languages, we can also write data to a CSV file using Python Pandas.
Pandas to_csv()
Python pandas provides the to_csv() method to convert data to a CSV file. If a file argument is provided, the output is written to a file. Otherwise, the CSV string is returned. It has so many attributes, but here we have mentioned only the most used attributes.
dataframe.to_csv(path,sep,na_rep,float_format, columns, header, index, mode, compression)
path- File path, if we leave it blank or none, the result is returned as a string.
sep- the string delimiter of length 1 for the output file.
na_rep- the string represents the missing data.
float_format- the string format for floating point numbers.
columns- optional, columns or sequence to write.
header- default True, list of column names.
index - default True, row names.
mode- write mode, default 'w'.
compression- represents the compression mode, the possible values are 'infer', 'gzip', 'bz2', 'zip', 'xz', None and the default is 'infer'.
Example1: Write dataframe to CSV Python
Here is the simple code to write a dataframe to a CSV file.
import pandas as pd
# dictionary of lists
stu_dict = {'Name': ["Smith", "Priska", "Kashyap", "Andy"]
,'Subject': ["Phy", "Maths", "Chm", "Bio"],
'Marks': [90, 99, 92, 89]}
df = pd.DataFrame(stu_dict)
# write dataframe to csv
df.to_csv('highest_score.csv')
Once you run the above code, it generates and saves the CSV file in your working directory. You can also specify the full file path.
Example2: Write specific dataframe values to CSV
Here, we write some specific columns of dataframe to a CSV file.
import pandas as pd
# dictionary of lists
stu_dict = {'Name': ["Smith", "Priska", "Kashyap", "Andy"],
'Class':["6A","10A","8B","9C"],
'Subject': ["Phy", "Maths", "Chm", "Bio"],
'Marks': [90, 99, 92, 89]}
df = pd.DataFrame(stu_dict,
columns = ['Name', 'Subject', 'Marks'])
# write dataframe to csv
df.to_csv('highest_score.csv', index = False, header = True)
Once you run the above code, it generates and saves the CSV file in your working directory.
Example3: Write multiple dataframes to a CSV file
Here, we write multiple dataframe values to a CSV file.
import pandas as pd
# dictionary of lists
pre_stu_dict = {'Name': ["Alisa", "Alya", "Kim", "Gaga"],
'Class':["1A","3C","2B","4A"],
'Subject': ["Eng", "Maths", "Sci", "GK"],
'Marks': [95, 98, 89, 93]}
sec_stu_dict = {'Name': ["Smith", "Priska", "Kashyap", "Andy"],
'Class':["6A","10A","8B","9C"],
'Subject': ["Phy", "Maths", "Chm", "Bio"],
'Marks': [90, 99, 92, 89]}
df1 = pd.DataFrame(pre_stu_dict,
columns = ['Name', 'Subject', 'Marks'])
df2 = pd.DataFrame(sec_stu_dict,
columns = ['Name', 'Subject', 'Marks'])
# write dataframes to csv
pd.concat([df1, df2]).to_csv('highest_score.csv',
index = False, header = True)
Once you run the above code, it generates and saves the CSV file in your working directory.
Related Articles
Python Pandas DataFrameConvert List to Dataframe Python
Convert dictionary to dataframe Python
Python Pandas CSV to Dataframe
Quick Introduction to Python Pandas
Python heap implementation
zip function in Python
Remove last element from list Python
Check if list is empty Python
Quick Introduction to Python Pandas
Python Pandas DataFrame
Python3 Tkinter Messagebox
Python Tkinter Geometry Managers
Python Tkinter Scale Widget
Python Tkinter Overview and Examples
Python Turtle Graphics Overview
Factorial Program in Python
Python snake game code with Pygame
Python JSON Tutorial - Create, Read, Parse JSON file
Python convert xml to dict
Python convert dict to xml