Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

How to save a DataFrame as csv file in Python?

Saving A DataFrame As Csv File

Hello folks! In this article, we will be focusing on the Technique to Save a DataFrame as a CSV(comma-separated values) file.

So let us begin!


What is Python Pandas Module?

Python has a number of to deal with the data and offer different functionalities altogether.

Python Pandas module helps us to deal with large values of data in terms of datasets. Thus, by using the Pandas module, we can manipulate the data values of huge datasets and deal with it.

Pandas deals with the data values and elements in the form of DataFrames. A DataFrame consists of rows and columns which can be altered and highlighted.

So, let us now focus on the creation of a DataFrame in Pandas module.


Creation of a DataFrame in Python

Have a look at the below code!

import os
import pandas
Domain = ["IT", "DATA_SCIENCE", "NETWORKING"] 

domain_dict = {'Domain': Domain} 

data_frame = pandas.DataFrame(domain_dict) 

So, we use pandas.DataFrame() function to create a data frame out of the passed data values in the form of Dictionary as seen above.

Output:

        Domain
0	IT
1	DATA_SCIENCE
2	NETWORKING

Having created a DataFrame, it’s now the time to save the DataFrame as a CSV file. Have a look at the below section for the same.


Saving a DataFrame as a CSV file

We often come across situations wherein we need to save the huge data created out of scrapping or analysis in an easy and readable rather shareable form.

Now, we can do this by saving the data frame into a csv file as explained below.

Syntax:

dataframe.to_csv('file.csv') 

The pandas.to_csv() function enables us to save a data frame as a CSV file. We need to pass the file name as a parameter to the function.

Let us have a look at the below example.

import pandas
Domain = ["IT", "DATA_SCIENCE", "NEYWORKING"] 

domain_dict = {'Domain': Domain} 

data_frame = pandas.DataFrame(domain_dict) 

data_frame.to_csv('DEMO.csv') 

Output:

DEMO -csv File
DEMO -csv File

Conclusion

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

Till then, Happy Learning!!