w3resource

Pandas: Convert a given list of lists into a Dataframe

Pandas: DataFrame Exercise-54 with Solution

Write a Pandas program to convert a given list of lists into a Dataframe.

Sample Solution :

Python Code :

import pandas as pd
my_lists = [['col1', 'col2'], [2, 4], [1, 3]]
# sets the headers as list
headers = my_lists.pop(0) 
print("Original list of lists:")
print(my_lists)
df = pd.DataFrame(my_lists, columns = headers)
print("New DataFrame")
print(df)

Sample Output:

Original list of lists:
[[2, 4], [1, 3]]
New DataFrame
   col1  col2
0     2     4
1     1     3    

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python Pandas program to convert DataFrame column type from string to datetime.
Next: Write a Pandas program to group by the first column and get second column as lists in rows.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Dictionary comprehension:

>>> m = {x: x ** 2 for x in range(5)}
>>> m
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}