Convert Python Dictionary into a Pandas Dataframe
Converting a Python dictionary into a Pandas dataframe can be achieved by separating the dictionary's keys and values into two separate columns.
The original dictionary contains dates as keys and corresponding values:
d = {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}
To create a dataframe from this dictionary, one can:
Utilize the DataFrame Constructor:
Pass the dictionary as an argument to the DataFrame constructor:
df = pd.DataFrame(d)
However, this approach may raise an error if the dictionary contains scalar values, as it expects multiple columns.
Extract Dictionary Items:
Extract key-value pairs from the dictionary as a list of tuples:
data = list(d.items())
And then create the dataframe using the DataFrame constructor:
df = pd.DataFrame(data)
This approach requires an additional step of assigning proper column names.
Create a Series:
Alternatively, one can create a Pandas Series from the dictionary, with the values as data and dates as index:
s = pd.Series(d, name='DateValue')
One can then reset the index to create a dataframe:
df = s.reset_index(name='Date')
This approach ensures that the dates become a column in the dataframe.
The above is the detailed content of How Can I Convert a Python Dictionary to a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!