Convert Dictionary to DataFrame in Python with column names
Last Updated :
26 Feb, 2024
In Python, the pandas library provides a powerful and flexible tool for working with tabular data through its DataFrame class. When creating a DataFrame from a dictionary, it’s common to set the keys of the dictionary as the column names of the resulting DataFrame. In this article, we will see how we can create a Pandas DataFrame from a dictionary as keys as column names.
Python DataFrame from Dictionary as Keys as Column Name
Below are some of the ways to achieve this task in Python:
- Using pd.DataFrame() Method
- Using list() method
- Using Series() method
Using pd.DataFrame() Method
In this example, a Python dictionary students
containing names as keys and corresponding marks as values is converted to a Pandas DataFrame using pd.DataFrame()
. The resulting DataFrame df
displays the names and marks in tabular form with columns labeled ‘Name’ and ‘Marks’.
Python3
import pandas as pd
students = { "Shravan" : 90 , "Jeetu" : 91 , "Ram" : 32 , "Pankaj" : 95 }
df = pd.DataFrame(students.items(), columns = [ 'Name' , 'Marks' ])
print (df)
|
Output:
Name Marks
0 Shravan 90
1 Jeetu 91
2 Ram 32
3 Pankaj 95
Using list() method
In this example, a Python dictionary students
with names as keys and corresponding marks as values is converted into a Pandas DataFrame using pd.DataFrame(list(students.items()), columns=['Name', 'Marks'])
. The resulting DataFrame df
presents the names and marks in tabular form with columns labeled ‘Name’ and ‘Marks’.
Python3
import pandas as pd
students = { "Shravan" : 90 , "Jeetu" : 91 , "Ram" : 32 , "Pankaj" : 95 }
df = pd.DataFrame( list (students.items()), columns = [ 'Name' , 'Marks' ])
print (df)
|
Output:
Name Marks
0 Shravan 90
1 Jeetu 91
2 Ram 32
3 Pankaj 95
Using Series() method
In this example, a Python dictionary students
with names as keys and corresponding scores as values is initially converted to a Pandas Series using pd.Series(students, name='Score')
. Subsequently, the series is transformed into a DataFrame df
with column names ‘Name’ and ‘Score’ by resetting the index and renaming the columns accordingly.
Python3
import pandas as pd
students = { "Shravan" : 90 , "Jeetu" : 91 , "Ram" : 32 , "Pankaj" : 95 }
series = pd.Series(students, name = 'Score' )
df = pd.DataFrame(series)
df.reset_index(inplace = True )
df.columns = [ 'Name' , 'Score' ]
print (df)
|
Output:
Name Score
0 Shravan 90
1 Jeetu 91
2 Ram 32
3 Pankaj 95
Share your thoughts in the comments
Please Login to comment...