Python嵌套字典按数值区间分组统计各区间元素数量实现问题
实现方案
方案1:纯Python输出目标字典
先明确区间判定规则和示例完全对齐:
1-3:词频≤33-5:3<词频≤55-7:5<词频≤77-10:7<词频≤1010+:词频>10
实现代码:
# 初始输入字典 raw_data = { 938742158: {'car': 3, 'yes': 5, 'none': 6, 'bi': 5, 'new': 4, 'service': 2, 'color': 8, 'have': 6, 'back': 5}, 938735955: {'car': 5, 'my': 11, 'note': 5, 'dir': 3, 'led': 6, 'r': 3, 'line': 10} } def count_bucket(word_counts): # 初始化所有区间计数为0 res = {'1-3': 0, '3-5': 0, '5-7': 0, '7-10': 0, '10+': 0} for cnt in word_counts.values(): if cnt <= 3: res['1-3'] += 1 elif cnt <= 5: res['3-5'] += 1 elif cnt <= 7: res['5-7'] += 1 elif cnt <= 10: res['7-10'] += 1 else: res['10+'] += 1 return res # 遍历所有文本id生成结果 result = {text_id: count_bucket(counts) for text_id, counts in raw_data.items()}
打印结果和你预期完全一致:
print(result) # 输出:{938742158: {'1-3': 2, '3-5': 4, '5-7': 2, '7-10': 1, '10+': 0}, 938735955: {'1-3': 2, '3-5': 2, '5-7': 1, '7-10': 1, '10+': 1}}
方案2:输出Pandas DataFrame格式
如果需要转为表格形式的DataFrame,追加以下代码即可:
import pandas as pd df = pd.DataFrame.from_dict(result, orient='index') # 可选:将文本id从索引转为普通列 df = df.reset_index().rename(columns={'index': '文本id'}) print(df)
输出效果:
| 文本id | 1-3 | 3-5 | 5-7 | 7-10 | 10+ |
|---|---|---|---|---|---|
| 938742158 | 2 | 4 | 2 | 1 | 0 |
| 938735955 | 2 | 2 | 1 | 1 | 1 |
内容的提问来源于stack exchange,提问作者uckocaman
相关产品推荐
相关产品推荐

