Convert Python dict into a dataframe
Easily convert a Python dict into a DataFrame with pd.DataFrame.from_dict(dict)
. The dict's keys will automatically become columns and the values, assuming they are list-like, will form rows.
The result is a 2x2 DataFrame with columns 'A' and 'B'. Easy, right?
Detailed walkthrough
Start with a simple dictionary
For dictionaries with list-like values, use pd.DataFrame.from_dict()
as shown above.
Time is of the essence
If your dictionary keys are dates and the values are single scalars, it's better to have dates as an index. Here's how:
Now, Date
and DateValue
will clearly display your time-series data.
How about "date"-ing the right way?
If your dates are grumpy and don't want to follow datetime
format, pd.to_datetime
is your friend:
This transforms your Date
column into Timestamp
objects. They're not only cool, but also useful for time series analysis.
Look, a single-value dictionary!
When every key-value pair is feeling lonesome (read: single scalar value), kindly provide an index
:
The first snippet gives you keys as column headers, while the second reveres rows over columns.
No space? No problem!
If you're dealing with chunky dictionaries or you're just trying to save memory space, consider using row-oriented external storage like Parquet or Feather:
You can read these back into a DataFrame with pd.read_parquet()
and pd.read_feather()
respectively. Remember, tidy data is happy data.
Other interesting scenarios
Working with JSON
Creating a DataFrame from a list of dictionaries is as easy as pie. It's especially useful when your data is in JSON format:
In this case, a single list item corresponds to a row in the DataFrame. Neat, huh?
Mind your orientation
Some dictionaries are not like the others. This is where the orient
parameter comes in handy:
When you find your dictionary dancing to its beat, orient
is your dance partner.
Was this article helpful?