如何在Pandas DataFrame中提取methods列的嵌套字典值
提取Pandas DataFrame嵌套字典列为单独列的解决方案
问题背景
用户拥有如下结构的Pandas DataFrame:
df= pd.DataFrame({'methods': {0: {'get': 12, 'post': 4, 'put': 1, 'delete': 1, 'patch': 0, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0}, 1: {'get': 13, 'post': 4, 'put': 1, 'delete': 1, 'patch': 0, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0}, 2: {'get': 13, 'post': 4, 'put': 1, 'delete': 1, 'patch': 0, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0}, 3: {'get': 3, 'post': 1, 'put': 2, 'delete': 1, 'patch': 1, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0, 'parameters': {'$numberDouble': 'NaN'}}, 4: {'get': 3, 'post': 1, 'put': 2, 'delete': 1, 'patch': 1, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0, 'parameters': {'$numberDouble': 'NaN'}}}, 'averageNumberOfOperationsPerPath': {0: 1.2857142857142851, 1: 1.266666666666666, 2: 1.266666666666666, 3: 3.333333333333333, 4: 3.333333333333333}, 'api_spec_id': {0: 84, 1: 84, 2: 84, 3: 124, 4: 124}})
需要将methods列中的get、post、put等字段提取为单独列,尝试过eval()函数及以下代码但未成功:
df1 = df.pop('methods').str.strip('{').str.split(':',expand=True).astype(float)
可行实现方案
方法1:使用pd.json_normalize()直接展开嵌套字典
pd.json_normalize()是处理嵌套字典/JSON结构的专用工具,能一键将methods列的字典展开为单独列,还会自动处理额外的parameters嵌套字段:
# 展开methods列的字典为新DataFrame methods_df = pd.json_normalize(df['methods']) # 将展开后的列与原DataFrame合并(若需保留原其他列) result_df = pd.concat([df.drop('methods', axis=1), methods_df], axis=1)
方法2:过滤指定字段后展开
如果只需要提取HTTP方法相关字段(忽略parameters),可以先过滤字典内容,再用apply(pd.Series)展开:
# 定义需要提取的HTTP方法列表 http_methods = ['get', 'post', 'put', 'delete', 'patch', 'head', 'options', 'trace', 'connect'] # 过滤每个字典,仅保留指定字段,再展开为列 methods_df = df['methods'].apply(lambda x: {k: v for k, v in x.items() if k in http_methods}).apply(pd.Series) # 合并到原DataFrame result_df = pd.concat([df.drop('methods', axis=1), methods_df], axis=1)
结果说明
- 方法1会保留所有字段,包括
parameters.$numberDouble列; - 方法2仅保留指定的HTTP方法字段,更贴合只提取方法计数的需求。
内容的提问来源于stack exchange,提问作者Brie MerryWeather
相关产品推荐
相关产品推荐

