Home >Backend Development >Python Tutorial >How to Convert a Python Dictionary to a Pandas DataFrame?

How to Convert a Python Dictionary to a Pandas DataFrame?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 17:26:14366browse

How to Convert a Python Dictionary to a Pandas DataFrame?

Converting a Python Dictionary to a DataFrame

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn