Home >Backend Development >Python Tutorial >How to Efficiently Convert a Python Dictionary to a Pandas DataFrame?
Given a Python dictionary with keys as dates and values as corresponding values, one may need to convert this object into a pandas DataFrame with columns representing the dates and the values.
pd.DataFrame constructor expects multiple columns with data, but providing scalar values as in the case of a dictionary throws a ValueError.
Passing the dictionary's items (key-value pairs) directly to the constructor resolves this issue:
pd.DataFrame(d.items()) # or list(d.items()) in python 3
A more efficient approach is to utilize the pd.Series constructor:
s = pd.Series(d, name='DateValue')
This creates a pandas Series with the values from the dictionary and a custom name. To add the dates as a column, set the index name to 'Date' and reset the index to obtain the desired DataFrame:
s.index.name = 'Date' s.reset_index()
These methods provide efficient ways to convert a Python dictionary into a pandas DataFrame, allowing for easy data manipulation and analysis.
The above is the detailed content of How to Efficiently Convert a Python Dictionary to a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!