You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于pandas单列生成值组合并为原表批量新增自定义列

实现代码

import pandas as pd
from itertools import combinations

# 核心处理逻辑
for idx1, idx2 in combinations(df.index, 2):
    # 取组合对应的Name生成列名,方便后续识别
    name_1 = df.loc[idx1, "Name"]
    name_2 = df.loc[idx2, "Name"]
    # 初始化新列默认值为1
    new_col = pd.Series([1]*df.shape[0], index=df.index)
    # 按规则赋值2和1.5
    new_col.loc[idx1] = 2
    new_col.loc[idx2] = 1.5
    # 拼接至原DataFrame
    df[f"{name_1}_{name_2}_weight"] = new_col

补充说明

  • 上述代码基于无重复的两两Name组合生成对应新列,新列命名规则可根据需求自行调整。
  • 若需要生成有序两两组合(即同时生成A对应2、B对应1.5和B对应2、A对应1.5两种列),只需将combinations替换为itertools.permutations即可。

内容的提问来源于stack exchange,提问作者Akshit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 18:06:04