JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

How to Convert a Python Dictionary to a Pandas DataFrame

Author:JIYIK Last Updated:2025/05/02 Views:

We will cover methods for dictionaryconverting Python to Pandas , as well as options for using as and as values ​​and converting nested to .datafarmekeyscolumnsvaluesrowdictionaryDataFrame

We will also introduce another method using pandas.DataFrame.from_dict to chain it with any of the rename methods and set the names of the index and columns in one go.


Methods for 字典converting to PandasDataFame

Pandas DataFrame Constructor pd.DataFrame()If you pass dictionary items as arguments to the constructor instead of the dictionary itself, then the dictionary is converted to a dataframe.

# python 3.x
import pandas as pd

fruit_dict = {3: "apple", 2: "banana", 6: "mango", 4: "apricot", 1: "kiwi", 8: "orange"}

print(pd.DataFrame(list(fruit_dict.items()), columns=["Quantity", "FruitName"]))

The sum of the dictionaries will be converted DataFrameto two columns with the column names given in the options.

   Quantity FruitName
0         3     apple
1         2    banana
2         6     mango
3         4   apricot
4         1      kiwi
5         8    orange

Methods to Convert to and from in Pandas DataFrame

We can simply put the dictionary in square brackets and remove the column names from the above code, like this:

import pandas as pd

fruit_dict = {1: "apple", 2: "banana", 3: "mango", 4: "apricot", 5: "kiwi", 6: "orange"}

print(pd.DataFrame([fruit_dict]))

Output:

       1       2      3        4     5       6
0  apple  banana  mango  apricot  kiwi  orange

We will use pandas's 字典推导sum concatto combine all of them 字典, and then pass the list to use the new列名

Consider the following code,

import pandas as pd

data = {"1": {"apple": 11, "banana": 18}, "2": {"apple": 16, "banana": 12}}
df = pd.concat({k: pd.Series(v) for k, v in data.items()}).reset_index()
df.columns = ["dict_index", "name", "quantity"]
print(df)

Output:

  dict_index    name  quantity
0          1   apple        11
1          1  banana        18
2          2   apple        16
3          2  banana        12

pandas.DataFrame().from_dict()Method to convert dict to dataframe

We will use from_dict to convert the dict to a dataframe, here we set orient = index to use the dictionary keys as rows and use rename()the method to change the column names.

Consider the following code,

import pandas as pd

print(
    pd.DataFrame.from_dict(
        {"apple": 3, "banana": 5, "mango": 7, "apricot": 1, "kiwi": 8, "orange": 3},
        orient="index",
    ).rename(columns={0: "Qunatity"})
)

Output:

         Quantity
apple           3
banana          5
mango           7
apricot         1
kiwi            8
orange          3

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to Convert DataFrame Column to String in Pandas

Publish Date:2025/05/02 Views:161 Category:Python

We will look at methods for converting Pandas DataFrame columns to strings. Pandas Series.astype(str) Method DataFrame.apply() Methods operate on the elements in a column We will use the same DataFrame below in this article. import pandas a

How to count the frequency of values in a Pandas DataFrame

Publish Date:2025/05/02 Views:84 Category:Python

Sometimes, when you use DataFrame , you may want to count the number of times a value occurs in a column, or in other words, calculate the frequency. There are mainly three methods used for this. Let's look at them one by one. df.groupby().

How to get value from Pandas DataFrame cell

Publish Date:2025/05/02 Views:147 Category:Python

We'll look at using to get values ​​from cells in iloc Pandas , which is great for selecting by position, and how it differs from . We'll also learn about the and methods, which we can use when we don't want to set the return type to .

How to Add a Row to a Pandas DataFrame

Publish Date:2025/05/02 Views:127 Category:Python

Pandas is designed to load a fully populated DataFrame . We can pandas.DataFrame add them one by one in . This can be done by using various methods, such as .loc , dictionary, pandas.concat() or DataFrame.append() . .loc [index] Add rows to

How to change the order of Panas DataFrame columns

Publish Date:2025/05/02 Views:184 Category:Python

We will show how to use insert and reindex to change the order of columns in different ways pandas.DataFrame , such as assigning column names in a desired order. pandas.DataFrame Sort the columns in the new order The easiest way is columns

How to pretty print an entire Pandas Series/DataFrame

Publish Date:2025/05/02 Views:167 Category:Python

We will introduce various methods to pretty print the entire Pandas Series/DataFrame, such as option_context, set_option, and options.display. option_context Pretty Printing Pandas DataFrame We can option_context use with one or more option

How to Convert a Pandas Dataframe to a NumPy Array

Publish Date:2025/05/02 Views:151 Category:Python

We will introduce to_numpy() the method to pandas.Dataframe convert a to NumPy an array, which is introduced in pandas v0.24.0, replacing the old .values method. We can define it on Index , Series , and DataFrame objects to_numpy . The old

How to add a header row to a Pandas DataFrame

Publish Date:2025/05/02 Views:161 Category:Python

We will look at methods for adding a header row to a pandas dataframe, as well as the option to pass in the names directly in the dataframe or by assigning the column names in a list directly to dataframe.columns the method. We will also in

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial