Problem:
Given a Python dictionary with keys representing dates and values representing corresponding values, the task is to convert it into a Pandas DataFrame with two columns: one for dates and the other for values.
Answer:
To perform this conversion, we can take the following steps:
Direct Conversion:
import pandas as pd d = {'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(d, columns=['Date', 'DateValue'])
Via Series:
If passing the dictionary directly to the DataFrame constructor leads to errors, we can create a Pandas Series first and then reset its index:
s = pd.Series(d, name='DateValue') s.index.name = 'Date' df = s.reset_index()
The above is the detailed content of How to Convert a Python Dictionary to a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!