Sometimes, we want to convert a Python dict into a Pandas DataFrame.
In this article, we’ll look at how to convert a Python dict into a Pandas DataFrame.
How to convert a Python dict into a Pandas DataFrame?
To convert a Python dict into a Pandas DataFrame, we can use the DataFrame
constructor with an iterator with the tuples of the key-value pairs.
For instance, we write:
import pandas as pd
d = {
u'2012-06-08': 388,
u'2012-06-09': 388,
u'2012-06-10': 388,
u'2012-06-11': 389,
u'2012-06-12': 389,
u'2012-06-13': 389
}
df = pd.DataFrame(d.items())
print(df)
to convert the d
dictionary to a DataFrame.
We call d.items
to return the iterator with the tuples of the key-value pairs and use that as the argument of DataFrame
.
And then we assign the returned DataFrame to df
.
Therefore, we get:
0 1
0 2012-06-08 388
1 2012-06-09 388
2 2012-06-10 388
3 2012-06-11 389
4 2012-06-12 389
5 2012-06-13 389
as the value of df
.
Conclusion
To convert a Python dict into a Pandas DataFrame, we can use the DataFrame
constructor with an iterator with the tuples of the key-value pairs.