6  Exporting Data Frames

For these examples we will use a familiar dataset of products:

Code
from pandas import read_csv

request_url = "https://raw.githubusercontent.com/prof-rossetti/intro-to-python/main/data/products.csv"
df = read_csv(request_url)
df.head()
id name aisle department price
0 1 Chocolate Sandwich Cookies cookies cakes snacks 3.50
1 2 All-Seasons Salt spices seasonings pantry 4.99
2 3 Robust Golden Unsweetened Oolong Tea tea beverages 2.49
3 4 Smart Ones Classic Favorites Mini Rigatoni Wit... frozen meals frozen 6.99
4 5 Green Chile Anytime Sauce marinades meat preparation pantry 7.99

6.1 To List of Dictionaries (“Records” Format)

We can convert a DataFrame to a list of dictionaries, using the to_dict method:

products = df.to_dict("records") # CONVERT TO LIST OF DICT

print(type(products))
print(type(products[0]))
products[0]
<class 'list'>
<class 'dict'>
{'id': 1,
 'name': 'Chocolate Sandwich Cookies',
 'aisle': 'cookies cakes',
 'department': 'snacks',
 'price': 3.5}
FYI

Here, the “records” parameter value has nothing to do with any of the columns in the dataset, but rather the format in which to export the data. The “records” format refers to a list of dictionaries.

6.2 To CSV File

We can use the to_csv method to export a DataFrame to a CSV file.

As a parameter, we specify the name of the CSV file that should be created (in this case, “products_copy.csv”), as well as whether or not to include the index as a column in the resulting file:

df.to_csv("products_copy.csv", index=False)

In Colab, the file will be saved to the Colab Filesystem, where we have the ability to download the file to our local machine.