How to create a pandas DataFrame using a list of lists?

PandasServer Side ProgrammingProgramming

The pandas DataFrame can be created by using the list of lists, to do this we need to pass a python list of lists as a parameter to the pandas.DataFrame() function.

Pandas DataFrame will represent the data in a tabular format, like rows and columns. If we create a pandas DataFrame using a list of lists, the inner list will be transformed as a row in the resulting list.

Example

# importing the pandas package
import pandas as pd
# creating a nested list
nested_list = [[1,2,3],[10,20,30],[100,200,300]]

# creating DataFrame
df = pd.DataFrame(nested_list, columns= ['A','B','C'])

print(df)# displaying resultant DataFrame

Explanation

In this above Example, nested_list is having 3 sub-lists and each list is having 3 integer elements, by using the DataFrame constructor we create a DataFrame or a table shape of 3X3. The columns parameter is used to customize the default column labels from [0,1,2] to [A,B,C]. The resultant DataFrame can be seen below.

Output

    A    B    C
0   1    2    3
1   10   20   30
2   100  200  300

The output DataFrame has 3 rows and 3 columns, with column label representation as A, B, C.

Example

# importing the pandas package
import pandas as pd
# creating a nested list
nested_list = [['A','B','C'],['D','E'],['F','G','H']]

# creating DataFrame
df = pd.DataFrame(nested_list)

# displaying resultant DataFrame
print(df)

Explanation

In this following example, we have created a pandas DataFrame object using the list of lists with different lengths. The second inner list has only 2 elements and the remaining inner lists have 3 elements, due to this we will get None value in the resultant DataFrame.

Output

    0   1     2
0   A   B     C
1   D   E  None
2   F   G     H

We can see that there is a none value in the second-row third elements, which is due to the uneven length of inner lists.

raja
Updated on 17-Nov-2021 08:29:35

Advertisements