Pandas新手求助:如何将主分类字符串合并至子分类并移除主分类
解决Pandas中按分类层级拼接字符串并移除父分类条目问题
步骤1:构造示例数据
先把你提供的表格转换成Pandas DataFrame:
import pandas as pd data = { 'id': ['3.ab.3.', '3.ab.3.a.', '3.ab.3.b.', '3.ab.4.', '3.ab.4.a.', '3.ab.4.b.', '3.ab.4.b.1', '3.ab.4.b.2'], 'string': ['axz', 'b', 'c', 'dog', 'e', 'f', 'g', 'h'] } df = pd.DataFrame(data)
步骤2:筛选出叶子节点(无下级分类的条目)
我们需要保留没有子分类的条目,判断标准是:没有其他id以当前id为前缀(且长度更长)。
# 判断每个id是否是叶子节点:没有其他id以它为前缀 is_leaf = ~df['id'].apply(lambda x: df['id'].str.startswith(x).sum() > 1) leaf_df = df[is_leaf].copy()
步骤3:构建id到字符串的映射字典
方便快速查找父分类的字符串内容:
id_str_map = df.set_index('id')['string'].to_dict()
步骤4:拼接所有父分类的字符串
编写函数,为每个叶子节点找到所有上层父分类,拼接它们的字符串后再加上自身的字符串:
def assemble_full_string(current_id): parts = current_id.split('.') parent_ids = [] temp_parts = parts.copy() # 逐级向上查找存在的父分类id while len(temp_parts) > 1: temp_parts.pop() candidate_id = '.'.join(temp_parts) # 处理id结尾有无.的情况 if candidate_id in id_str_map: parent_ids.append(candidate_id) elif candidate_id + '.' in id_str_map: parent_ids.append(candidate_id + '.') # 拼接父分类字符串和自身字符串 return ''.join([id_str_map[pid] for pid in parent_ids]) + id_str_map[current_id] # 应用函数到叶子节点的string列 leaf_df['string'] = leaf_df['id'].apply(assemble_full_string)
最终结果
执行完上述代码后,leaf_df就是你期望的结果:
print(leaf_df)
输出:
id string 1 3.ab.3.a. axzb 2 3.ab.3.b. axzc 4 3.ab.4.a. doge 6 3.ab.4.b.1 dogfg 7 3.ab.4.b.2 dogfh
内容的提问来源于stack exchange,提问作者priyal shah
相关产品推荐
相关产品推荐

