如何在Pandas中提取content列的id并统计次数后合并至原DataFrame?
问题描述
我在Pandas的DataFrame中有一列名为content(同时包含其他多列),该列的值示例如下:
data = { 24686: [ { 'id': 'new-required-request-property', 'text': "added the new required request property 'todaySubsectionList'", 'level': 0, 'operation': 'PUT', 'path': '/frequent' } ], 85961: '', 80955: "Backward compatibility errors (1):\nerror at original_source=/Users/, in API GET /api/v2/templates api path removed without deprecation [api-path-removed-without-deprecation].", 26854: [ { 'id': 'request-parameter-removed', 'text': "deleted the 'header' request parameter 'Accept'", 'level': 1, 'operation': 'GET', 'path': '/reviews' }, { 'id': 'request-parameter-removed', 'text': "deleted the 'header' request parameter 'Content-Type'", 'level': 1, 'operation': 'GET', 'path': '/reviews' } ], 30896: [], 54673: [], 31920: [], 6421: '' } df = pd.DataFrame(data.items(), columns=['index', 'content'])
需要提取其中的id字段并统计其出现次数,将结果追加至原DataFrame中,期望输出格式如下:
content count new-required-request-property,request-parameter-removed 1,2
解决方案
可以通过自定义函数结合Pandas的apply方法实现,具体步骤如下:
编写处理函数:针对
content列的每个元素,提取其中的id并统计频次:from collections import Counter def extract_id_counts(content): # 过滤掉空字符串、空列表等无效内容 if not isinstance(content, list) or len(content) == 0: return ('', '') # 提取所有id字段 ids = [item.get('id', '') for item in content if isinstance(item, dict) and 'id' in item] # 统计频次 count_result = Counter(ids) # 按要求格式拼接结果:id用逗号分隔,对应次数也用逗号分隔 id_str = ','.join(count_result.keys()) count_str = ','.join(map(str, count_result.values())) return (id_str, count_str)应用函数并拆分结果到新列:
# 应用函数,得到包含id字符串和次数字符串的元组列 df[['content_ids', 'count']] = df['content'].apply(lambda x: pd.Series(extract_id_counts(x))) # 替换原content列为提取后的id字符串(匹配示例输出的列名) df = df.drop(columns=['content']).rename(columns={'content_ids': 'content'}) # 过滤掉空内容的行(可选,按需执行) df = df[df['content'] != '']生成最终合并格式:
如果需要将所有结果合并为一行(如示例中的输出格式),执行以下代码:final_df = pd.DataFrame({ 'content': [','.join(df['content'])], 'count': [','.join(df['count'])] })此时输出的
final_df即为:content count new-required-request-property,request-parameter-removed 1,2
内容的提问来源于stack exchange,提问作者Brie MerryWeather
相关产品推荐
相关产品推荐

