How do I create a pandas dataframe from a dict?
I have a Python dictionary:
{u'2012-07-01': 391,
u'2012-07-02': 392,
u'2012-07-03': 392,
u'2012-07-04': 392,
u'2012-07-05': 392,
u'2012-07-06': 392}
I want to convert this into a pandas dataframe where the dates become one column and their corresponding values form another column. The expected output should look like:
Date DateValue
0 2012-07-01 391
1 2012-07-02 392
2 2012-07-03 392
. 2012-07-04 392
. ... ...
Is there a direct way to create a pandas dataframe from a dict like this?
I’ve worked with Pandas for a while, and the easiest way I’ve found is to directly convert the dictionary into a DataFrame using from_dict()
. Here’s how:"
import pandas as pd
data = {
'2012-07-01': 391,
'2012-07-02': 392,
'2012-07-03': 392,
'2012-07-04': 392,
'2012-07-05': 392,
'2012-07-06': 392
}
df = pd.DataFrame.from_dict(data, orient='index', columns=['DateValue']).reset_index()
df.rename(columns={'index': 'Date'}, inplace=True)
print(df)
This method is great if you want your dictionary keys (dates) as a column in your DataFrame.
Building on the first answer, if you want a cleaner syntax, you can use pd.DataFrame()
with items()
. It simplifies the conversion process:
df = pd.DataFrame(list(data.items()), columns=['Date', 'DateValue'])
This is a straightforward way to create a pandas dataframe from dict while keeping things simple.
Another interesting approach, especially if you’re already working with Pandas Series, is to first convert the dictionary into a Series and then into a DataFrame. This can be useful if you’re doing further operations on it later:
df = pd.Series(data).reset_index()
df.columns = ['Date', 'DateValue']
print(df)
This method leverages Pandas Series before converting it into a pandas dataframe from dict, making it flexible for additional manipulations.