- Convert List to DataFrame in Python
- Convert list of lists to DataFrame in Pandas
- Frequently Asked:
- Convert Lists of tuples to DataFrame in Pandas
- Convert List of lists to DataFrame & set column names and indexes
- Convert List of tuples to DataFrame and skip certain columns
- Convert multiple lists to DataFrame in Pandas
- Related posts:
- Как преобразовать список в DataFrame в Python
- Пример 1: преобразование одного списка в фрейм данных
- Пример 2. Преобразование нескольких списков в DataFrame
- Пример 3: преобразование списка списков в фрейм данных
- Дополнительные ресурсы
- Convert a List to Pandas Dataframe (with examples)
- Examples of Converting a List to Pandas DataFrame
- Example 1: Convert a List
- Example 2: Convert a List of Lists
- Check the Object Type
- Applying Stats Using Pandas (optional)
- An Opposite Scenario
Convert List to DataFrame in Python
In this article, we will discuss how to convert a single or multiple lists to a DataFrame.
Table Of Contents
Python’s pandas library provide a constructor of DataFrame to create a Dataframe by passing objects i.e.
pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
Here data parameter can be a numpy ndarray, lists, dict, or an other DataFrame. Also, columns and index are for column and index labels. Let’s use this to convert lists to dataframe object from lists.
Convert list of lists to DataFrame in Pandas
Frequently Asked:
# List of lists students = [ ['jack', 34, 'Sydeny'] , ['Riti', 30, 'Delhi' ] , ['Aadi', 16, 'New York'] ]
Pass this list to DataFrame’s constructor to create a dataframe object i.e.
import pandas as pd # Creating a DataFrame object from list of lists dfObj = pd.DataFrame(students) # Display the DataFrame print(dfObj)
Contents of the created DataFrames are as follows,
0 1 2 0 jack 34 Sydeny 1 Riti 30 Delhi 2 Aadi 16 New York
Convert Lists of tuples to DataFrame in Pandas
Just like list of lists we can pass list of tuples in dataframe constructor to create a dataframe.
Suppose we have a list of tuples i.e.
# List of Tuples students = [ ('jack', 34, 'Sydeny') , ('Riti', 30, 'Delhi' ) , ('Aadi', 16, 'New York') ]
Pass this list of tuples to DataFrame’s constructor to create a DataFrame object i.e.
import pandas as pd # Creating a DataFrame object from list of tuple dfObj = pd.DataFrame(students) # Display the DataFrame print(dfObj)
Contents of the created dataframe is as follows,
0 1 2 0 jack 34 Sydeny 1 Riti 30 Delhi 2 Aadi 16 New York
Both Column & Index labels are default. But we can also provide them i.e.
Convert List of lists to DataFrame & set column names and indexes
import pandas as pd # List of lists students = [ ['jack', 34, 'Sydeny'] , ['Riti', 30, 'Delhi' ] , ['Aadi', 16, 'New York'] ] # Convert list of tuples to dataframe and # set column names and indexes dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'City'], index=['a', 'b', 'c']) # Display the DataFrame print(dfObj)
Contents of the created dataframe is as follows,
Name Age City a jack 34 Sydeny b Riti 30 Delhi c Aadi 16 New York
Convert List of tuples to DataFrame and skip certain columns
What of in our list of tuples we have 3 entries in each tuple. What if we want to use 1st and 3rd entry only? Let’s create a dataframe by skipping 2nd entry in tuples i.e.
import pandas as pd # List of Tuples students = [ ('jack', 34, 'Sydeny') , ('Riti', 30, 'Delhi' ) , ('Aadi', 16, 'New York') ] # Create datafrae from student list of tuples # but skip column 'Age' i.e. only with 2 columns dfObj = pd.DataFrame.from_records( students, exclude=['Age'], columns = ['Name' , 'Age', 'City'], index=['a', 'b', 'c']) # Display the DataFrame print(dfObj)
Contents of the created dataframe is as follows,
Name City a jack Sydeny b Riti Delhi c Aadi New York
This DataFrame has only two columns because we skipped the middle entry from each of the tuple in list.
Convert multiple lists to DataFrame in Pandas
Suppose we have 3 different lists and we want to convert them to a DataFrame, with each list as a column. To do that,
zip the lists to create a list of tuples and create a dataframe with this zipped lists i.e.
import pandas as pd listOfNames = ['Jack', 'Riti', 'Aadi'] listOfAge = [34, 30, 16] listOfCity = ['Sydney', 'Delhi', 'New york'] # Create a zipped list of tuples from above lists zippedList = list(zip(listOfNames, listOfAge, listOfCity)) # Create a dataframe from zipped list dfObj = pd.DataFrame(zippedList, columns = ['Name' , 'Age', 'City'], index=['a', 'b', 'c']) # Display the DataFrame print(dfObj)
Contents of the created dataframe is as follows,
Name Age City a Jack 34 Sydney b Riti 30 Delhi c Aadi 16 New york
The Complete example is as follows,
import pandas as pd students = [['jack', 34, 'Sydeny'] , ['Riti', 30, 'Delhi' ] , ['Aadi', 16, 'New York'] ] print("****Create a Dataframe from list of lists *****") # Creating a dataframe object from listoftuples dfObj = pd.DataFrame(students) print("Dataframe : " , dfObj, sep='\n') # List of Tuples students = [('jack', 34, 'Sydeny') , ('Riti', 30, 'Delhi' ) , ('Aadi', 16, 'New York') ] print("****Create a Dataframe from list of tuple *****") # Creating a dataframe object from listoftuples dfObj = pd.DataFrame(students) print("Dataframe : " , dfObj, sep='\n') print("****Create a Dataframe from list of tuple, also set column names and indexes *****") #Convert list of tuples to dataframe and set column names and indexes dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'City'], index=['a', 'b', 'c']) print("Dataframe : " , dfObj, sep='\n') print("****Create dataframe from list of tuples and skip certain columns*********") # Create datafrae from student list but # skip column 'Age' i.e. only with 2 columns dfObj = pd.DataFrame.from_records( students, exclude=['Age'], columns = ['Name' , 'Age', 'City'], index=['a', 'b', 'c']) print("Dataframe : " , dfObj, sep='\n') print("***Create dataframe from multiple lists***") listOfNames = ['jack', 'Riti', 'Aadi'] listOfAge = [34, 30, 16] listOfCity = ['Sydney', 'Delhi', 'New york'] # Create a zipped list of tuples from above lists zippedList = list(zip(listOfNames, listOfAge, listOfCity)) print("zippedList = " , zippedList) # Create a dataframe from zipped list dfObj = pd.DataFrame(zippedList, columns = ['Name' , 'Age', 'City'], index=['a', 'b', 'c']) print("Dataframe : " , dfObj, sep='\n')
****Create a Dataframe from list of lists ***** Dataframe : 0 1 2 0 jack 34 Sydeny 1 Riti 30 Delhi 2 Aadi 16 New York ****Create a Dataframe from list of tuple ***** Dataframe : 0 1 2 0 jack 34 Sydeny 1 Riti 30 Delhi 2 Aadi 16 New York ****Create a Dataframe from list of tuple, also set column names and indexes ***** Dataframe : Name Age City a jack 34 Sydeny b Riti 30 Delhi c Aadi 16 New York ****Create dataframe from list of tuples and skip certain columns********* Dataframe : Name City a jack Sydeny b Riti Delhi c Aadi New York ***Create dataframe from multiple lists*** zippedList = [('jack', 34, 'Sydney'), ('Riti', 30, 'Delhi'), ('Aadi', 16, 'New york')] Dataframe : Name Age City a jack 34 Sydney b Riti 30 Delhi c Aadi 16 New york
We learned about different ways to convert list to a Pandas DataFrame in Python.
Related posts:
Как преобразовать список в DataFrame в Python
Часто вам может понадобиться преобразовать список в DataFrame в Python.
К счастью, это легко сделать с помощью функции pandas.DataFrame , которая использует следующий синтаксис:
pandas.DataFrame(данные = Нет, индекс = Нет, столбцы = Нет, …)
- data: данные для преобразования в DataFrame
- index: Индекс для использования в результирующем DataFrame
- столбцы: метки столбцов для использования в результирующем DataFrame.
В этом руководстве представлено несколько примеров использования этой функции на практике.
Пример 1: преобразование одного списка в фрейм данных
В следующем коде показано, как преобразовать один список в кадр данных pandas:
import pandas as pd #create list that contains points scored by 10 basketball players data = [4, 14, 17, 22, 26, 29, 33, 35, 35, 38] #convert list to DataFrame df = pd.DataFrame(data, columns=['points']) #view resulting DataFrame print(df) points 0 4 1 14 2 17 3 22 4 26 5 29 6 33 7 35
Пример 2. Преобразование нескольких списков в DataFrame
В следующем коде показано, как преобразовать несколько списков в DataFrame pandas:
import pandas as pd #define lists points = [4, 14, 17, 22, 26, 29, 33, 35, 35, 38] rebounds = [1, 4, 4, 5, 8, 7, 5, 6, 9, 11] #convert lists into a single list data = [] data.append(points) data.append(rebounds) #view new list data [[4, 14, 17, 22, 26, 29, 33, 35, 35, 38], [1, 4, 4, 5, 8, 7, 5, 6, 9, 11]] #convert list into DataFrame df = pd.DataFrame(data). transpose () df.columns =['points', 'rebounds'] #view resulting DataFrame df points rebounds 0 4 1 1 14 4 2 17 4 3 22 5 4 26 8 5 29 7 6 33 5 7 35 6 8 35 9 9 38 11
Пример 3: преобразование списка списков в фрейм данных
В следующем коде показано, как преобразовать список списков в кадр данных pandas:
import pandas as pd #define list of lists data = [[4, 1], [14, 4], [17, 4], [22, 5], [26, 8], [29, 7], [33, 5], [35, 6], [35, 9], [38,11]] #convert list into DataFrame df = pd.DataFrame(data, columns=['points', 'rebounds']) #view resulting DataFrame df points rebounds 0 4 1 1 14 4 2 17 4 3 22 5 4 26 8 5 29 7 6 33 5 7 35 6 8 35 9 9 38 11
Вы можете использовать следующий код, чтобы быстро проверить, сколько строк и столбцов находится в результирующем DataFrame:
#display number of rows and columns in DataFrame df.shape (10, 2)
Мы видим, что полученный DataFrame имеет 10 строк и 2 столбца.
И мы можем использовать следующий код для получения имен столбцов в результирующем DataFrame:
#display column names of DataFrame list(df) ['points', 'rebounds']
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные задачи в pandas:
Convert a List to Pandas Dataframe (with examples)
At times, you may need to convert a list to Pandas DataFrame in Python.
You may then use the following template to convert your list to a DataFrame:
import pandas as pd list_name = ['item_1', 'item_2', 'item_3', . ] df = pd.DataFrame(list_name, columns=['column_name'])
In the next section, you’ll see how to perform the conversion in practice.
Examples of Converting a List to Pandas DataFrame
Example 1: Convert a List
Let’s say that you have the following list that contains 5 products:
products_list = ['laptop', 'printer', 'tablet', 'desk', 'chair']
You can then apply the following syntax in order to convert the list of products to Pandas DataFrame:
import pandas as pd products_list = ['laptop', 'printer', 'tablet', 'desk', 'chair'] df = pd.DataFrame(products_list, columns=['product_name']) print(df)
This is the DataFrame that you’ll get:
product_name 0 laptop 1 printer 2 tablet 3 desk 4 chair
Example 2: Convert a List of Lists
How would you then convert a list of lists to a DataFrame?
For instance, let’s say that you have the following list of lists:
products_list = [['laptop', 1300], ['printer', 150], ['tablet', 300], ['desk', 450], ['chair', 200]]
You can then run the code below to perform the conversion to a DataFrame:
import pandas as pd products_list = [['laptop', 1300], ['printer', 150], ['tablet', 300], ['desk', 450], ['chair', 200]] df = pd.DataFrame(products_list, columns=['product_name', 'price']) print(df)
And this is the result that you’ll get:
product_name price 0 laptop 1300 1 printer 150 2 tablet 300 3 desk 450 4 chair 200
Alternatively, you may have your list of lists as follows:
products_list = [['laptop', 'printer', 'tablet', 'desk', 'chair'], [1300, 150, 300, 450, 200]]
Therefore, the Python code to perform the conversion to a DataFrame would be:
import pandas as pd products_list = [['laptop', 'printer', 'tablet', 'desk', 'chair'], [1300, 150, 300, 450, 200]] df = pd.DataFrame(products_list).transpose() df.columns = ['product_name', 'price'] print(df)
Run the code, and you’ll get the same DataFrame:
product_name price 0 laptop 1300 1 printer 150 2 tablet 300 3 desk 450 4 chair 200
Check the Object Type
If needed, you may also check the type of the objects (e.g., List vs. DataFrame) by applying this code:
import pandas as pd products_list = [['laptop', 'printer', 'tablet', 'desk', 'chair'], [1300, 150, 300, 450, 200]] df = pd.DataFrame(products_list).transpose() df.columns = ['product_name', 'price'] print('products_list: ' + str(type(products_list))) print('df: ' + str(type(df)))
Applying Stats Using Pandas (optional)
Once you converted your list into a DataFrame, you’ll be able to perform an assortment of operations and calculations using Pandas.
For instance, you may use Pandas to derive some statistics about your data.
In the context of our example, you can apply the code below in order to get the mean, max and min price using Pandas:
import pandas as pd products_list = [['laptop', 'printer', 'tablet', 'desk', 'chair'], [1300, 150, 300, 450, 200]] df = pd.DataFrame(products_list).transpose() df.columns = ['product_name', 'price'] mean_value = df['price'].mean() max_value = df['price'].max() min_value = df['price'].min() print('The mean price is: ' + str(mean_value)) print('The max price is: ' + str(max_value)) print('The min price is: ' + str(min_value))
Run the Python code, and you’ll get these stats:
The mean price is: 480 The max price is: 1300 The min price is: 150
An Opposite Scenario
Sometimes, you may face an opposite situation, where you’ll need to convert a DataFrame into a list. If that’s the case, you may want to check the following guide that explains the steps to perform the conversion.