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
Release: 2024-12-07 17:26:14
Original
328 people have browsed it

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'])
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template