如何将Pandas DataFrame与字典进行关联?
关联DataFrame与字典并统计数值数量
场景1:统计DataFrame中各数值的出现次数并转为字典
如果你的需求是统计16个单元格里不同数值(如0、1)的数量,并存入字典,可以用以下方法:
- 先构造示例DataFrame(4×4共16个单元格):
import pandas as pd df = pd.DataFrame({ 'col1': [0, 1, 0, 1], 'col2': [1, 0, 1, 0], 'col3': [0, 0, 1, 1], 'col4': [1, 1, 0, 0] })
- 用
stack()扁平化DataFrame后统计,直接转为字典:
# 统计数值出现次数并转为字典 value_counts = df.stack().value_counts().to_dict() print(value_counts) # 示例输出:{0: 8, 1: 8}
- 手动遍历统计(适合自定义逻辑):
count_dict = {} # 遍历所有单元格 for _, row in df.iterrows(): for val in row: count_dict[val] = count_dict.get(val, 0) + 1 print(count_dict)
场景2:将字典映射关系应用到DataFrame
如果是要把字典的键值对作为映射规则,替换DataFrame中的数值(比如把0换成特定标签):
# 定义映射字典 map_dict = {0: '未达标', 1: '达标'} # 应用映射 df_mapped = df.replace(map_dict) print(df_mapped)
内容的提问来源于stack exchange,提问作者GUNNAM SUBBA RAO
相关产品推荐
相关产品推荐

