如何将DataFrame列中的聚类编号批量替换为指定新值?
解决方案
首先,我们可以通过创建映射字典的方式,将原聚类编号与目标新编号一一对应,再用Pandas的内置方法快速完成替换操作。
步骤1:定义映射规则
把你给出的原聚类编号列表,和对应的递增新编号(从0开始)做成字典:
# 原聚类编号列表 original_clusters = [0, 4, 8, 25, 26, 95, 98, 144, 175] # 生成映射字典:原编号 → 新编号(0到8) cluster_mapping = {old_id: new_id for new_id, old_id in enumerate(original_clusters)}
这个字典会自动生成{0:0, 4:1, 8:2, ..., 175:8}的对应关系,完全匹配你的替换规则。
步骤2:生成新列
假设原聚类编号存储在df_new的cluster列中,直接用map()方法生成新列:
df_new['new'] = df_new['cluster'].map(cluster_mapping)
处理异常情况(可选)
如果df_new中存在不在上述9个编号里的聚类值,map()会把这些值转为NaN。你可以用fillna()给它们设置默认值(比如-1):
df_new['new'] = df_new['cluster'].map(cluster_mapping).fillna(-1).astype(int)
如果希望保留原异常值,改用replace()方法即可:
df_new['new'] = df_new['cluster'].replace(cluster_mapping)
批量处理多列(如果需要)
如果你的DataFrame每行有多个聚类相关列需要替换,比如cluster_1、cluster_2等,可以批量操作:
# 指定需要替换的列列表 target_cols = ['cluster_1', 'cluster_2', 'cluster_3'] # 批量替换并生成新列 for col in target_cols: df_new[f'{col}_new'] = df_new[col].map(cluster_mapping)
内容的提问来源于stack exchange,提问作者JEG
相关产品推荐
相关产品推荐

