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

如何将含列表值的嵌套字典转换为可用的DataFrame?

嵌套字典转DataFrame及后续操作实现

问题描述

现有如下结构的嵌套字典,单个hash下的ids、weights、values、measure_dates列表长度一致,不同hash的列表长度随测量次数变化,需要将其转换为可操作的DataFrame,并完成两个需求:

  1. 找出测量次数最多的hash,要求用nlargest()或sort_values().head()实现;
  2. 找出values平均值在指定区间内的hash。

示例字典:

{
    'IRR-99876-UTY': {
        'ids': [9912234, 9912237, 45555889],
        'weights': [0.09, 0.09, 0.113],
        'values': [2.31220, 2.31219, 2.73944],
        'measure_dates': ['2021-10-14', '2021-10-15', '2022-12-17']
    },
    'IRR-10881-CKZ': {
        'ids': [45557231],
        'weights': [0.31],
        'values': [5.221001],
        'measure_dates': ['2022-12-31']
    },
    'IRR-881-CKZ': {
        'ids': [24661, 24662, 29431],
        'weights': [0.05, 0.07, 0.105],
        'values': [3.254, 4.500001, 7.3221],
        'measure_dates': ['2018-05-05', '2018-05-06', '2018-07-01']
    }
}

解决方案

1. 嵌套字典转DataFrame

通过pd.DataFrame.from_dict结合explode方法,将每个hash的每条测量记录拆分为单独行:

import pandas as pd

# 定义示例字典
data = {
    'IRR-99876-UTY': {
        'ids': [9912234, 9912237, 45555889],
        'weights': [0.09, 0.09, 0.113],
        'values': [2.31220, 2.31219, 2.73944],
        'measure_dates': ['2021-10-14', '2021-10-15', '2022-12-17']
    },
    'IRR-10881-CKZ': {
        'ids': [45557231],
        'weights': [0.31],
        'values': [5.221001],
        'measure_dates': ['2022-12-31']
    },
    'IRR-881-CKZ': {
        'ids': [24661, 24662, 29431],
        'weights': [0.05, 0.07, 0.105],
        'values': [3.254, 4.500001, 7.3221],
        'measure_dates': ['2018-05-05', '2018-05-06', '2018-07-01']
    }
}

# 转换为初始DataFrame,将hash作为列
df = pd.DataFrame.from_dict(data, orient='index').reset_index().rename(columns={'index': 'hash'})
# 展开所有列表类型的列,每条测量记录单独成行
df = df.explode(['ids', 'weights', 'values', 'measure_dates'], ignore_index=True)
# 转换数据类型(按需调整)
df['ids'] = df['ids'].astype(int)
df['weights'] = df['weights'].astype(float)
df['values'] = df['values'].astype(float)
df['measure_dates'] = pd.to_datetime(df['measure_dates'])

转换后的DataFrame结构示例:

hashidsweightsvaluesmeasure_dates
IRR-99876-UTY99122340.092.312202021-10-14
IRR-99876-UTY99122370.092.312192021-10-15
IRR-99876-UTY455558890.1132.739442022-12-17
IRR-10881-CKZ455572310.315.2210012022-12-31
IRR-881-CKZ246610.053.2542018-05-05

2. 找出测量次数最多的hash

先按hash分组统计测量次数,再用nlargest()或sort_values()筛选:

# 统计每个hash的测量次数
count_df = df.groupby('hash').size().reset_index(name='measure_count')

# 方法1:用nlargest取测量次数最多的1个hash
top_hash = count_df.nlargest(1, 'measure_count')

# 方法2:用sort_values排序后取头部
top_hash = count_df.sort_values('measure_count', ascending=False).head(1)

print(top_hash)

3. 找出values平均值在指定区间内的hash

按hash分组计算values的平均值,再筛选符合区间条件的记录:

# 计算每个hash的values平均值
mean_df = df.groupby('hash')['values'].mean().reset_index(name='values_mean')

# 指定目标区间,例如2到5之间
lower_bound = 2
upper_bound = 5

# 筛选符合条件的hash
filtered_hashes = mean_df[(mean_df['values_mean'] >= lower_bound) & (mean_df['values_mean'] <= upper_bound)]

print(filtered_hashes)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:50:29