How to Create a CSV File in Python
Pandas to the rescue
In this article, you’ll learn how to construct a CSV file in Python. This can be a great way to save data on which you’ll later do some analysis. A lot of articles start with reading from such a CSV file or DataFrame
.
So, you must know how to construct such a file yourself as a data enthusiast. It allows you to play around with, change, and create large CSVs yourself. These files can be found all over the web and playing around with them is a great way to get started with data science.
Installing Pandas
We’ll be using a library named Pandas. Pandas has been around since 2008 and is a flexible, powerful data analysis and manipulation tool. It’s very efficient with small data up to 1GB. If you have a larger file, consider reading it in chunks before moving to a more complex library.
import pandas as pd
Writing to the CSV File
Before we can write something to a CSV file, we have to create a dictionary first. Personally, I like to construct an equal-sized list for each column. That way, we can construct a dictionary in a very readable way:
data_frame = {'room': rooms, 'swimming pool': pools, 'price': prices}
Now that we have a dictionary containing all the data, let’s proceed. With this dictionary in place, we instantiate a DataFrame
:
data_frame = pd.DataFrame(data=my_data)
The DataFrame
allows us to present data in a way that is suitable for data analysis. It also offers multiple methods of data filtering and other utilities. One of those utilities is to export the data to a CSV, which is exactly what we need!
data_frame.to_csv('data.csv')
Conclusion
Just like many other things, creating a CSV file is easy in Python. In this article, we’ve seen a very readable way to create such a file.
If you found this helpful or have something interesting to add, please let me know in a comment down below.
Interested in personal training or coaching? Mail me at info@kwal-it.be or visit our site for our other services.