Python dataframe list to columns

Create Pandas DataFrame from Python List

In this lesson, you will learn how to convert Python List to a pandas DataFrame. It covers creating DataFrame from different types of a list like single list, multiple lists, nested lists. It creates DataFame from a list where a list can be added as a row or a column.

The List is a simple data structure in Python that stores the values as a List. The List can have heterogeneous elements, i.e., it can have values of different types. To analyze such a List, we can convert it into the pandas DataFrame. By converting the List into a 2-dimensional structure makes it efficient to process.

DataFrame can be created from List using DataFrame constructor. This article discusses all the cases of it in detail.

Table of contents

Create DataFrame from list using constructor

DataFrame constructor can create DataFrame from different data structures in python like dict , list, set, tuple, and ndarray .

Читайте также:  Css интервал между элементами

In the below example, we create a DataFrame object using a list of heterogeneous data. By default, all list elements are added as a row in the DataFrame. And row index is the range of numbers(starting at 0).

import pandas as pd # Create list fruits_list = ['Apple', 10, 'Orange', 55.50] print(fruits_list) # Create DataFrame from list fruits_df = pd.DataFrame(fruits_list) print(fruits_df)
['Apple', 10, 'Orange', 55.5] 0 0 Apple 1 10 2 Orange 3 55.5

Create DataFrame from list with a customized column name

While creating a DataFrame from the list, we can give a customized column label in the resultant DataFrame. By default, it provides a range of integers as column labels, i.e., 0, 1, 2…n.

We can specify column labels into the columns=[col_labels] parameter in the DataFrame constructor.

In the below example, we create DataFrame from a list of fruit names and provides a column label as “Fruits”.

import pandas as pd # Create list fruits_list = ['Apple', 'Banana', 'Orange','Mango'] print(fruits_list) # Create DataFrame from list fruits_df = pd.DataFrame(fruits_list, columns=['Fruits']) print(fruits_df)
['Apple', 'Banana', 'Orange', 'Mango'] Fruits 0 Apple 1 Banana 2 Orange 3 Mango

Create DataFrame from list with a customized index

As we just discussed the changing column label, we can even customize the row index as well. We can give a meaningful row index to identify each row uniquely. It becomes easier to access the rows using the index label.

We can specify row index into the index=[row_index1, row_index2] parameter in the DataFrame constructor. By default, it gives a range of integers as row index i.e. 0, 1, 2…n.

Let’s see how we can provide the custom row index while creating DataFrame from the List.

import pandas as pd # Create list fruits_list = ['Apple', 'Banana', 'Orange','Mango'] print(fruits_list) # Create DataFrame from list fruits_df = pd.DataFrame(fruits_list, index=['Fruit1', 'Fruit2', 'Fruit3', 'Fruit4']) print(fruits_df)
['Apple', 'Banana', 'Orange', 'Mango'] 0 Fruit1 Apple Fruit2 Banana Fruit3 Orange Fruit4 Mango

Create DataFrame from list by changing data type

While converting a Python List to the DataFrame, we may need to change the values’ data type.

We can change the data type of the list elements using the dtype parameter of the DataFrame constructor.

Suppose we have a list of fruit’s prices of type object. But, while creating DataFrame we need to correct its data type to float64. In such case we use dtype parameter as shown below example.

import pandas as pd # Create list price_list = ['50', '100', '60', '20'] print(price_list) # Create DataFrame from list price_df = pd.DataFrame(price_list) print("Data type before : ", price_df.dtypes) # Create DataFrame from list with type change price_df = pd.DataFrame(price_list, dtype='float64') print("Data type after : ", price_df.dtypes) print(price_df)
['50', '100', '60', '20'] Data type before : 0 object dtype: object Data type after : 0 float64 dtype: object 0 0 50.0 1 100.0 2 60.0 3 20.0

Create DataFrame from hierarchical lists as rows

It may be possible to have data scattered into multiple lists or in the list of lists, also called a multi-dimensional list. In such a case, We can pass such a list to the DataFrame constructor to convert it into the DataFrame. By default, it adds each list as a row in the resultant DataFrame.

In the below example, we have a list that has lists of fruit names and their prices. DataFrame constructor will add both the lists as a separate row in the resulting DataFrame.

import pandas as pd # Create list fruits_list = [['Apple', 'Banana', 'Orange', 'Mango'],[120, 40, 80, 500]] print(fruits_list) # Create DataFrame from list fruits_df = pd.DataFrame(fruits_list) print(fruits_df)
[['Apple', 'Banana', 'Orange', 'Mango'], [120, 40, 80, 500]] 0 1 2 3 0 Apple Banana Orange Mango 1 120 40 80 500

Create DataFrame from Hierarchical lists as columns

As discussed in the above section, we have a multi-dimensional list, but we do not want them to add to the DataFrame as a row. Instead, we want to add each list as a separate column in the DataFrame. For that, we need to use the transpose() function.

In the below example, we have a list of two lists, fruit names and another for the fruits’ price. And we want to add both the list as a separate column in the DataFrame.

import pandas as pd # Create list fruits_list = [['Apple', 'Banana', 'Orange', 'Mango'],[120, 40, 80, 500]] print(fruits_list) # Create DataFrame from list fruits_df = pd.DataFrame(fruits_list).transpose() print(fruits_df)
[['Apple', 'Banana', 'Orange', 'Mango'], [120, 40, 80, 500]] 0 1 0 Apple 120 1 Banana 40 2 Orange 80 3 Mango 500

Create DataFrame from multiple lists

It is the most common use case in the industry where you have multiple separate lists, and you need to add them as different columns in the DataFrame. This case can be resolved by following two ways:

The below example demonstrates the use of zip() function to combine multiple lists in one list and pass it to the DataFrame constructor.

import pandas as pd # Create multiple lists fruits_list = ['Apple', 'Banana', 'Orange', 'Mango'] price_list = [120, 40, 80, 500] # Create DataFrame fruits_df = pd.DataFrame(list(zip(fruits_list, price_list )), columns = ['Name', 'Price']) print(fruits_df)
Name Price 0 Apple 120 1 Banana 40 2 Orange 80 3 Mango 500

The below example demonstrates the use of Python dictionary data structure to solve the purpose. Here, column names are keys of the dict and, lists are the values of dict which need to be added in the DataFrame.

import pandas as pd # Create multiple lists fruits_list = ['Apple', 'Banana', 'Orange', 'Mango'] price_list = [120, 40, 80, 500] # Create dict fruits_dict = print(fruits_dict) # Create DataFrame from dict fruits_df = pd.DataFrame(fruits_dict) print(fruits_df) 
 Name Price 0 Apple 120 1 Banana 40 2 Orange 80 3 Mango 500

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Convert List to pandas DataFrame in Python (3 Examples)

TikTok Icon Statistics Globe

On this page you’ll learn how to create a pandas DataFrame from a list object in the Python programming language.

The page will consist of three examples for the creation of a pandas DataFrame from a list object. To be more precise, the content of the page looks as follows:

Creating Example Data

We use the following list object as a basis for this Python tutorial:

my_list = [1, 2, 3, 4, 5] # Create example list print(my_list) # Print example list # [1, 2, 3, 4, 5]

As you can see, our list contains five integer elements ranging from the values 1 to 5.

Example 1: Convert List to pandas DataFrame Column

In Example 1, I’ll show how to construct a new pandas DataFrame based on a list using the Python programming language.

For the following tutorial, we’ll first need to import the pandas library:

import pandas as pd # Import pandas library to Python

In the next step, we can use the DataFrame function of the pandas library to convert our example list to a single column in a new pandas DataFrame:

my_data1 = pd.DataFrame('x': my_list>) # Create pandas DataFrame from list print(my_data1) # Print pandas DataFrame

table 1 DataFrame convert list pandas dataframe python

Table 1 illustrates that our new pandas DataFrame is composed of five rows and one column. The values in this column correspond to the values in our list.

Example 2: Convert Each List Element to Separate Column of pandas DataFrame

In this example, I’ll show how to create a pandas DataFrame with a new variable for each element in a list.

We can do this in two steps. First, we have to initialize our pandas DataFrame using the DataFrame function. Second, we have to set the column names of our DataFrame.

Consider the Python syntax below:

my_data2 = pd.DataFrame([my_list]) # Each list element as column my_data2.columns = ['x1', 'x2', 'x3', 'x4', 'x5'] # Change column names print(my_data2) # Print pandas DataFrame

table 2 DataFrame convert list pandas dataframe python

By running the previous syntax, we have created Table 2, i.e. another data set containing one row and a separate column for each element in our list.

Example 3: Add List as New Column to Existing pandas DataFrame

This example explains how to append a list object as a new column to an already existing pandas DataFrame.

For this, we first have to create an exemplifying DataFrame:

my_data3 = pd.DataFrame('x1':range(1, 6), # Create pandas DataFrame 'x2':range(7, 2, - 1), 'x3':range(12, 17)>) print(my_data3) # Print pandas DataFrame

table 3 DataFrame convert list pandas dataframe python

As shown in Table 3, we have created a new pandas DataFrame consisting of five rows and three columns.

Note that it’s important that the number of rows in this DataFrame are equal to the length of our list object.

In the next step, we can add our list object as a new variable to our pandas DataFrame:

my_data3['new_col'] = my_list # Add list to existing DataFrame print(my_data3) # Print pandas DataFrame

table 4 DataFrame convert list pandas dataframe python

As revealed in Table 4, the previous code has created an updated version of our input data set to which our list has been concatenated as a new variable.

Video & Further Resources

In case you need more information on the Python programming syntax of this article, you might watch the following video on my YouTube channel. I’m explaining the Python programming code of this article in the video.

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

If you accept this notice, your choice will be saved and the page will refresh.

accept

Accept YouTube Content

Besides that, you could have a look at some of the related articles on my website.

On this page you have learned how to convert a list to a pandas DataFrame in the Python programming language. In case you have any further questions or comments, please let me know in the comments.

Источник

Оцените статью