python dict to pandas DataFrame

python dict to pandas DataFrame

In Python, you can use the DataFrame function provided by the Pandas library to convert the data of the dictionary (dict) type into a Pandas DataFrame.
Here is a simple example:

# -*- coding:utf-8 -*-
import pandas as pd

# 定义一个字典类型的数据
data = {
    
    'name': ['Alice', 'Bob', 'Charlie'], 
        'age': [25, 30, 35],
        'gender': ['F', 'M', 'M']}

# 将字典转换为 DataFrame
df = pd.DataFrame.from_dict(data)

print(df)

output:

      name  age gender
0    Alice   25      F
1      Bob   30      M
2  Charlie   35      M

Define a dictionary type data data containing three fields of name, age and gender, and then use the from_dict function provided by Pandas to convert it into a DataFrame object df. Finally, you can use the print function to view the conversion results.
When using the from_dict function, if the key of the dictionary is not a string but other types (such as int or tuple, etc.), you need to specify the orient parameter to specify the data arrangement. For example, if the keys of the dictionary are integers, you can convert them using:

# -*- coding:utf-8 -*-
import pandas as pd

# 定义一个元素为整数类型的字典数据
data = {
    
    1: [25, 'F'], 
        2: [30, 'M'],
        3: [35, 'M']}

# 使用 from_dict 函数将字典转换为 DataFrame
df = pd.DataFrame.from_dict(data, orient='index', columns=['age', 'gender'])

print(df)

output:

   age gender
1   25      F
2   30      M
3   35      M

The code specifies that the orient parameter is index, which means that the index of the dictionary is used as the row index of the DataFrame; at the same time, the columns parameter is specified to specify the column names of the DataFrame.

Guess you like

Origin blog.csdn.net/programmer589/article/details/130331261