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

How Can I Convert a Python Dictionary to a Pandas DataFrame?

Linda Hamilton
Release: 2024-12-12 16:11:10
Original
586 people have browsed it

How Can I Convert a Python Dictionary to a Pandas DataFrame?

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}
Copy after login

To create a dataframe from this dictionary, one can:

  1. Utilize the DataFrame Constructor:

    Pass the dictionary as an argument to the DataFrame constructor:

    df = pd.DataFrame(d)
    Copy after login

    However, this approach may raise an error if the dictionary contains scalar values, as it expects multiple columns.

  2. Extract Dictionary Items:

    Extract key-value pairs from the dictionary as a list of tuples:

    data = list(d.items())
    Copy after login

    And then create the dataframe using the DataFrame constructor:

    df = pd.DataFrame(data)
    Copy after login

    This approach requires an additional step of assigning proper column names.

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

    One can then reset the index to create a dataframe:

    df = s.reset_index(name='Date')
    Copy after login

    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!

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