How to Export Pandas DataFrame to the CSV File
Export Pandas DataFrame to the CSV File
In this tutorial, you are going to learn how to Export Pandas DataFrame to the CSV File in Python programming language. Here in this tutorial, we will do the following things to understand exporting pandas DataFrame to CSV file:
- Create a new DataFrame.
- Export the DataFrame to CSV File.
Basic Structure
1. Create new DataFrame
We are going to export the following data to CSV File:
Name | Age | Score |
---|---|---|
John | 20 | 89 |
Sara | 21 | 78 |
Jack | 21 | 94 |
Ricky | 20 | 56 |
Now let’s write the Python program for that:
First, we will import the pandas module and then we will create DataFrame.
The following program simply creates a DataFrame and prints values:
# import pandas library first from pandas import DataFrame # import students DataFrame Students = {'Name': ['John','Sara','Jack','Ricky'], 'Age': [20,21,21,20], 'Score': [89,78,94,56] } df = DataFrame(Students, columns= ['Name', 'Age', 'Score']) print (df)
The output should be:
2. Export the DataFrame to CSV File
As given in the above program we have successfully created a DataFrame. Now to export the DataFrame to CSV file we are going to use the following function:
Where,
So the complete program should look like:
# Import pandas library first from pandas import DataFrame # Import students DataFrame Students = {'Name': ['John','Sara','Jack','Ricky'], 'Age': [20,21,21,20], 'Score': [89,78,94,56] } # Create DataFrame df = DataFrame(Students, columns= ['Name', 'Age', 'Score']) # Export DataFrame to CSV File export_csv = df.to_csv (r'C:\Users\CrazyGeeks\Desktop\dataframe.csv', index = None, header=True) print (df)
The output file exported to desktop (C:\Users\CrazyGeeks\Desktop\dataframe.csv):
The exported CSV file looks like:
3. Another Example
If you don’t want to specify the specific location then you can just enter the name of the file. The exported file will be stored in the current directory where the program is located.
# Import pandas library first from pandas import DataFrame # Import students DataFrame Students = {'Name': ['John','Sara','Jack','Ricky'], 'Age': [20,21,21,20], 'Score': [89,78,94,56] } # Create DataFrame df = DataFrame(Students, columns= ['Name', 'Age', 'Score']) # Export DataFrame to CSV File without specific location export_csv = df.to_csv ('dataframe.csv', index = None, header=True) print (df)
Conclusion
You have successfully learned How to Export Pandas DataFrame to the CSV File. If you have any queries please don’t forget to comment out.
LATEST POSTS
-
numpy.where() in Python with Examples
-
C strcat() function with example
-
numpy.dot() in Python
-
How to Upgrade PIP in Windows
-
Python string strip() method
-
Binary Search in C++
-
numpy.reshape() in Python
-
numpy.ones() in Python
-
numpy.loadtxt() in Python
-
numpy.dtype() in Python
-
Java Math abs() method with examples
-
Java String Substring