如何从给定DataFrame创建指定结构的嵌套字典(布尔值转0/1)
实现方案
你可以用两种方式实现,逻辑都很简单,结果完全匹配你的要求:
方法1:直观遍历写法(易读性高,小数据量首选)
import pandas as pd # 定义需要处理的三列宝箱字段,避免重复写列名 chest_columns = ["chest_gold", "chest_silver", "chest_bronze"] # 布尔值转整数:pandas中布尔类型直接转int即可自动实现TRUE→1、FALSE→0的映射 df[chest_columns] = df[chest_columns].astype(int) # 初始化最终结果字典 nested_dict = {} # 逐行读取表数据,按层级写入字典 for _, row in df.iterrows(): current_profile = row["profile"] current_level = row["level"] # 如果当前profile还没作为外层键存入字典,先初始化对应的空内层字典 if current_profile not in nested_dict: nested_dict[current_profile] = {} # 按顺序把金、银、铜宝箱的值组成列表,存入对应level键下 nested_dict[current_profile][current_level] = row[chest_columns].tolist()
运行后直接取值即可得到你要的效果:
print(nested_dict['a'][1]) # 输出 [1,0,1] print(nested_dict['a'][2]) # 输出 [0,0,1] print(nested_dict['a'][3]) # 输出 [0,1,1]
方法2:groupby写法(大数据量效率更高)
如果你的表行数比较多,用pandas内置的groupby逻辑代替显式for循环,运行速度会快很多,代码如下:
chest_columns = ["chest_gold", "chest_silver", "chest_bronze"] nested_dict = ( # 先把三列布尔值转为整数 df.assign(**{col: df[col].astype(int) for col in chest_columns}) # 按profile分组 .groupby("profile") # 每个分组内,把level作为键、三个宝箱值组成的列表作为值,生成内层字典 .apply(lambda group: dict(zip(group["level"], group[chest_columns].values.tolist()))) # 最后把分组结果转为外层字典 .to_dict() )
两种写法输出的结果完全一致,你可以根据自己的数据量和代码习惯选择。
内容的提问来源于stack exchange,提问作者ianux22
相关产品推荐
相关产品推荐

