如何将Pandas DataFrame按person_nid和behavior_type分组生成嵌套字典
Pandas DataFrame转指定嵌套字典实现方案
核心实现代码
你可以直接用嵌套分组结合to_dict方法完成转换,示例代码如下:
import pandas as pd # 假设你的原始DataFrame名为df,先按需把数值字段转成字符串(匹配示例输出格式) convert_cols = ['value', '1_months', '2_months', '6_months', '12_months', '24_months', '60_months'] df[convert_cols] = df[convert_cols].astype(str) # 第一种写法:循环实现,易读性高 result = {} for person_nid, person_df in df.groupby("person_nid"): behavior_map = {} for behavior_type, behavior_df in person_df.groupby("behavior_type"): # 剔除分组字段后把每行转成字典,组成列表 behavior_map[behavior_type] = behavior_df.drop(columns=["person_nid", "behavior_type"]).to_dict("records") # person_nid转成字符串匹配示例的键格式,本身是字符串可去掉str() result[str(person_nid)] = behavior_map
如果偏好更简洁的写法,可以用字典推导式实现:
result = { str(person_nid): { behavior_type: group.drop(columns=["person_nid", "behavior_type"]).to_dict("records") for behavior_type, group in person_df.groupby("behavior_type") } for person_nid, person_df in df.groupby("person_nid") }
注意说明
to_dict("records")会自动将DataFrame的每行转换为字典,多个行组成列表,完全匹配你要求的输出结构- 如果你不需要把数值转成字符串格式,删除开头的类型转换代码即可
- 若
person_nid字段本身就是字符串类型,去掉转换时的str()包装即可
内容的提问来源于stack exchange,提问作者Steven Arias
相关产品推荐
相关产品推荐

