You have some list or list of lists and you want to convert them into a Pandas DataFrame. For example, you have some data about fruit prices in a python lists and you want to create a DataFrame like this one.
Pandas DataFrame from a Single List –
Let’s first create a pandas DataFrame from a single list using the fruits names.
To create a DataFrame first we have to import the pandas library
# import pandas library import pandas as pd
Then create the list.
# fruit list fruits = ['Apple','Avocado','Banana','Coconut','Jackfruit','Orange']
Now, to turn this list into a pandas DataFrame, all we have to do is pass this list to pandas DataFrame constructor pd.DataFrame.
# create dataframe from list df = pd.DataFrame(fruits) print(df)
Now, you can see that index is looking good but we do not have a descriptive column name. To change the column name or the index, we can pass the labels to the pd.DataFrame columns and index argument.
# create dataframe from list df = pd.DataFrame(data=fruits, index= [1, 2, 3, 4, 5, 6], columns=['fruit']) df
Pandas DataFrame from Multiple Lists –
Now, let’s create a pandas dataframe from multiple lists using the zip function. To create a dataframe from multiple lists we have to first zip those list and convert them into a list. Then we pass them to the pandas dataframe.
# lists fruits = ['Apple','Avocado','Banana','Coconut','Jackfruit','Orange'] prices = [200, 200, 40, 30, 500, 70] # create dataframe using zip and list df = pd.DataFrame(list(zip(fruits, prices)), columns=['fruit', 'price']) df
Pandas DataFrame from List of Lists –
Now, let’s create the complete dataframe using list of lists. First create the list of lists and then pass it to the pd.DataFrame.
# list of lists fruits_data = [['Apple', '1 kg', 200], ['Avocado', '1 kg', 200], ['Banana', '1 kg', 40], ['Coconut', '1 piece', 30], ['Jackfruit', '1 piece', 500], ['Orange', '1 kg', 70]] # create df from list of lists df = pd.DataFrame(fruits_data, columns=['fruit','quantity','price']) df
That’s it. We learned how to create a dataframe from a list, from more than two lists and from lists of lists.
Related Posts –
- Create Pandas DataFrame from dictionary.
- Convert a Pandas DataFrame to a Dictionary.
- Create a Pandas Series from a list.
If you want to learn more about pandas, please subscribe to our blog below.