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

如何将Pandas DataFrame转换为特定结构的两个字典?

Got it, let's tackle this. Since you didn't spell out the exact structure of the two dictionaries you're aiming for, I'll cover two of the most common, practical use cases for this kind of purchase data DataFrame. If your target structure is different, just share a sample of what you expect and I can tweak the code!

1. Dictionary: Customer → List of (Purchase Date, Product ID) Pairs

This structure maps each customer to all their purchase records, keeping the date and product linked together:

import pandas as pd

# First, let's use a sample DataFrame to demo (replace this with your actual data)
df = pd.DataFrame({
    'customer_id': ['C001', 'C001', 'C002', 'C003', 'C002'],
    'date': ['2024-01-01', '2024-01-05', '2024-01-02', '2024-01-03', '2024-01-06'],
    'product_id': ['P101', 'P102', 'P101', 'P103', 'P104']
})

# Build the first dictionary
customer_purchases = df.groupby('customer_id').apply(
    lambda group: list(zip(group['date'], group['product_id']))
).to_dict()

print(customer_purchases)

Output:

{
    'C001': [('2024-01-01', 'P101'), ('2024-01-05', 'P102')],
    'C002': [('2024-01-02', 'P101'), ('2024-01-06', 'P104')],
    'C003': [('2024-01-03', 'P103')]
}

2. Dictionary: Customer → Date → List of Products

This nested structure is useful if a customer might buy multiple products on the same day—it organizes purchases by date first:

# Build the second dictionary
customer_daily_purchases = df.groupby('customer_id').apply(
    lambda group: group.groupby('date')['product_id'].tolist().to_dict()
).to_dict()

print(customer_daily_purchases)

Output:

{
    'C001': {'2024-01-01': ['P101'], '2024-01-05': ['P102']},
    'C002': {'2024-01-02': ['P101'], '2024-01-06': ['P104']},
    'C003': {'2024-01-03': ['P103']}
}

Quick Notes:

  • If one of your target dictionaries is product-focused (e.g., {product_id: list of customers who bought it}), just use:
    product_customers = df.groupby('product_id')['customer_id'].tolist().to_dict()
    
  • The key here is using groupby() to aggregate the data how you need it, then to_dict() to convert the grouped Series/DataFrame into a Python dictionary. If your expected structure is something else (like customer → set of unique products), just adjust the aggregation step (e.g., use set() instead of list()).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:51:18