Introduction
In this tutorial, we want to write a Pandas DataFrame to a CSV file. In order to do this, we use the to_csv() method of Pandas.
Import Libraries
First, we import the following python modules:
import pandas as pd
Create Pandas DataFrame
Next, we create a Pandas DataFrame with some example data from a dictionary:
data = {
"language": ["Python", "Python", "Java", "JavaScript"],
"framework": ["Django", "FastAPI", "Spring", "ReactJS"],
"users": [20000, 9000, 7000, 5000]
}
df = pd.DataFrame(data)
df
Write Pandas DataFrame to CSV File
Next, we would like to write the PySpark DataFrame to a CSV file. The file should have the following attributes:
- File should include a header with the column names.
- Columns of the file should be separated with semi-colon
;
. - File should not include the index of the DataFrame.
- Existing file should be overwritten.
- File path should be "data/frameworks.csv".
To do this, we use the to_csv() method of Pandas:
df.to_csv("data/frameworks.csv", sep=";", index=False)
Conclusion
Congratulations! Now you are one step closer to become an AI Expert. You have seen that it is very easy to write a Pandas DataFrame to a CSV file. We can simply use the to_csv() method of Pandas. Try it yourself!
Also check out our Instagram page. We appreciate your like or comment. Feel free to share this post with your friends.