You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将DataFrame指定字段转换为字典?含数据示例

Convert Specific DataFrame Fields to a Dictionary in Python

Got it, let's walk through how to turn your sample DataFrame data into a dictionary—we'll cover a few common structures depending on what you need.

First, let's replicate your data into a pandas DataFrame so we can work with it directly:

import pandas as pd

# Build the sample dataset
data_rows = [
    ["age", "age", "YES", "Unknown", "CAT", "Multiple ecohorts"],
    ["bill_other", "bill_other_m0", "YES", "0", "CAT", "Multiple Billing (other)"],
    ["bill_other", "bill_other_m1", "YES", "0", "CAT", "Multiple Billing (other)"],
    ["bill_other", "bill_other_m2", "YES", "0", "CAT", "Multiple Billing (other)"],
    ["bill_other", "bill_other_m3", "YES", "0", "CAT", "Multiple Billing (other)"],
    ["bill_other", "bill_other_m4", "YES", "0", "CAT", "Multiple Billing (other)"]
]

column_names = ["Parent_Attribute", "Attribute", "Y/N for Modelling", "Impute_Value", "Type", "Product Description"]
df = pd.DataFrame(data_rows, columns=column_names)

Now pick the approach that matches your desired dictionary structure:

1. List of Dictionaries (One per Row)

If you want each row's selected fields to be a standalone dictionary (stored in a list), use to_dict() with the orient='records' parameter after filtering your target columns:

# Choose which fields to include
target_fields = ["Attribute", "Impute_Value", "Type"]
row_dicts = df[target_fields].to_dict(orient='records')

print(row_dicts)

Sample output:

[
    {'Attribute': 'age', 'Impute_Value': 'Unknown', 'Type': 'CAT'},
    {'Attribute': 'bill_other_m0', 'Impute_Value': '0', 'Type': 'CAT'},
    {'Attribute': 'bill_other_m1', 'Impute_Value': '0', 'Type': 'CAT'},
    ...
]

2. Nested Dictionary (Grouped by Parent_Attribute)

If you want to group entries under their parent attribute, use groupby() to cluster rows and aggregate them into nested dictionaries:

# Group by Parent_Attribute, with child rows as dictionaries
nested_dict = df.groupby("Parent_Attribute")[["Attribute", "Impute_Value", "Type"]].apply(lambda x: x.to_dict('records')).to_dict()

print(nested_dict)

Sample output:

{
    'age': [{'Attribute': 'age', 'Impute_Value': 'Unknown', 'Type': 'CAT'}],
    'bill_other': [
        {'Attribute': 'bill_other_m0', 'Impute_Value': '0', 'Type': 'CAT'},
        {'Attribute': 'bill_other_m1', 'Impute_Value': '0', 'Type': 'CAT'},
        ...
    ]
}

3. Flat Dictionary (Attribute as Key)

If you want a simple key-value pair where each Attribute maps to a specific field (like Impute_Value), use set_index() to anchor the keys:

# Flat map: Attribute -> Impute_Value
flat_key_value_dict = df.set_index("Attribute")["Impute_Value"].to_dict()

print(flat_key_value_dict)

Sample output:

{
    'age': 'Unknown',
    'bill_other_m0': '0',
    'bill_other_m1': '0',
    'bill_other_m2': '0',
    ...
}

Just adjust the column names in the code to match exactly which fields you need to include in your final dictionary.

内容的提问来源于stack exchange,提问作者Shuvayan Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:56:47