In this tutorial, we will learn how to convert a list of dictionaries into a pandas DataFrame. This is a very common task when working with data, and pandas make it easy to do.
We will start by importing the necessary modules, then we will create a list of dictionaries.
Next, we will use the pandas DataFrame constructor to create a DataFrame from our list of dictionaries.
Finally, we will print out the contents of our DataFrame.
Convert list of dictionaries to pandas DataFrame
import pandas as pd my_list = [{'a': 'foo', 'b': 'bar'}, {'c': 'baz', 'd': 'qux'}] df = pd.DataFrame(my_list) print(df)
Output
a b c d 0 foo bar NaN NaN 1 NaN NaN baz qux
As you can see, our DataFrame contains two rows and four columns. The first row contains the data from the first dictionary in our list, and the second row contains the data from the second dictionary. Each column represents a key from one of the dictionaries, and the values are the corresponding values for those keys.
Now that we know how to convert a list of dictionaries into a pandas DataFrame, let’s see how we can use this to our advantage.
Suppose we have a list of customer data, and we want to create a DataFrame from it.
- We can do this by creating a dictionary for each customer, with the keys being the customer’s information (name, address, etc.) and the values being the corresponding values for those keys.
- Then, we can simply pass our list of dictionaries into the DataFrame constructor to create our DataFrame.
customer_list = [{'name': 'John Doe', 'address': '123 Main Street'}, {'name': 'Jane Smith', 'address': '456 Elm Street'}] customer_df = pd.DataFrame(customer_list) print(customer_df)
Output
name address 0 John Doe 123 Main Street 1 Jane Smith 456 Elm Street
As you can see, this is a very powerful way to create a DataFrame from data that is stored in a list of dictionaries. This can be very helpful when working with data that is stored in JSON format.