基于DataFrame同表class列的值对description列内容做缩写扩展
解决方案
原有代码问题
你遍历groupby返回的是分组后的DataFrame副本,对副本j的修改不会同步到原表,同时你没有对转换后的结果做赋值存储,自然无法合并回原DataFrame。
方案1:按行apply(更简洁,无需分组)
直接对每行做处理,自动匹配当前行class对应的缩写映射,不需要分组操作,代码如下:
def expand_abbreviation(row): # 取当前行class对应的缩写映射字典,无匹配时返回空字典避免报错 abbr_map = abb.get(row["class"], {}) # 拆分描述文本,逐词替换,未匹配到的缩写保留原词 words = row["description"].split() replaced_words = [abbr_map.get(word, word) for word in words] return " ".join(replaced_words) # 直接赋值到新列,也可以覆盖原description列 df["expanded_description"] = df.apply(expand_abbreviation, axis=1)
方案2:groupby+transform(保留分组逻辑)
如果要沿用分组的处理思路,用transform方法返回和原表索引对齐的序列,直接赋值即可,无需手动合并:
df["expanded_description"] = df.groupby("class")["description"].transform( # s.name对应当前分组的class值,直接从abb字典取对应映射 lambda s: s.str.split().apply(lambda x: " ".join([abb[s.name].get(e, e) for e in x])) )
效果示例
假设你的映射字典和测试数据如下:
# 示例缩写映射字典 abb = { "通信": {"IT": "Information Transport"}, "计算机": {"IT": "Information Technology"} } # 测试DataFrame df = pd.DataFrame({ "class": ["通信", "计算机", "通信", "计算机"], "description": ["IT 运维", "IT 开发", "IT 传输", "IT 算法"] })
处理后得到的结果如下:
| class | description | expanded_description |
|---|---|---|
| 通信 | IT 运维 | Information Transport 运维 |
| 计算机 | IT 开发 | Information Technology 开发 |
| 通信 | IT 传输 | Information Transport 传输 |
| 计算机 | IT 算法 | Information Technology 算法 |
内容的提问来源于stack exchange,提问作者keerthan shetty
相关产品推荐
相关产品推荐

