如何在Python中将DataFrame中字典的键值对拆分为多行
拆分DataFrame中字典列为多行的解决方案
假设你的输入DataFrame包含一列字典格式的数据(比如示例中的info_dict列),可以用以下两种常用方法实现拆分:
方法一:利用apply(pd.Series) + stack
import pandas as pd # 示例输入DataFrame df = pd.DataFrame({ 'id': [1, 2], 'name': ['张三', '李四'], 'info_dict': [{'a':1, 'b':2}, {'x':3, 'y':4, 'z':5}] }) # 1. 将字典列转为Series并堆叠,提取键值对 dict_df = df['info_dict'].apply(pd.Series).stack().reset_index(level=1, name='value') dict_df.rename(columns={'level_1': 'key'}, inplace=True) # 2. 合并原DataFrame的其他列与拆分后的键值对 result = df.drop('info_dict', axis=1).join(dict_df).reset_index(drop=True) print(result)
方法二:利用explode + 列表推导
import pandas as pd # 示例输入DataFrame df = pd.DataFrame({ 'id': [1, 2], 'name': ['张三', '李四'], 'info_dict': [{'a':1, 'b':2}, {'x':3, 'y':4, 'z':5}] }) # 1. 将每个字典转为(key, value)的列表 df['kv_pairs'] = df['info_dict'].apply(lambda d: list(d.items())) # 2. 展开列表为多行 df_exploded = df.explode('kv_pairs') # 3. 拆分键值对为单独列 df_exploded[['key', 'value']] = pd.DataFrame(df_exploded['kv_pairs'].tolist(), index=df_exploded.index) # 4. 清理多余列 result = df_exploded.drop(['info_dict', 'kv_pairs'], axis=1) print(result)
两种方法最终都会输出符合预期的多行结果,你可以根据自己的DataFrame结构调整列名(比如把info_dict换成你实际的字典列名)。
内容的提问来源于stack exchange,提问作者Zikra Noman
相关产品推荐
相关产品推荐

