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
Linda HamiltonOriginal
2024-12-12 16:11:10646browse

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}

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)

    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())

    And then create the dataframe using the DataFrame constructor:

    df = pd.DataFrame(data)

    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')

    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!

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