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

按id分组,基于DataFrame的start列值添加移位列并修改Name列

按ID分组处理DataFrame的解决方案

原始DataFrame:

id     Name     type    start
AAA    A         xx      yes
AAA    B         yy      no
AAA    C         xx      no
BBB    C         xx      yes
BBB    D         zz      no
BBB    B         yy      no

需求说明

  • 按id字段分组
  • 针对组内start值为"no"的行:
    • 将Name替换为同组内start值为"yes"的行的Name值
    • 新增NAG列存储该行原来的Name值;可选新增typeNAG列存储原来的type值
  • 最终移除start列

尝试的代码(未实现需求)

def n_issue(row):
    if row['start'] == "no":
        return row['issueLabel']
    else:
        pass

ag["nag"] = ag(n_issue, axis=1)

可行解决方案

基础版实现(满足核心需求)

import pandas as pd

# 构造原始数据(如果已有DataFrame可跳过此步)
df = pd.DataFrame({
    'id': ['AAA', 'AAA', 'AAA', 'BBB', 'BBB', 'BBB'],
    'Name': ['A', 'B', 'C', 'C', 'D', 'B'],
    'type': ['xx', 'yy', 'xx', 'xx', 'zz', 'yy'],
    'start': ['yes', 'no', 'no', 'yes', 'no', 'no']
})

# 按id分组,提取每组中start为yes的Name值
grouped_target = df.groupby('id')['Name'].apply(
    lambda x: x[df.loc[x.index, 'start'] == 'yes'].iloc[0]
).reset_index(name='target_name')

# 合并原始数据与分组得到的目标Name
merged_df = df.merge(grouped_target, on='id')

# 筛选start为no的行,处理列值
result = merged_df[merged_df['start'] == 'no'].copy()
result['NAG'] = result['Name']  # 保存原Name到NAG
result['Name'] = result['target_name']  # 替换Name为组内yes行的Name

# 移除多余列并调整顺序
result = result.drop(columns=['start', 'target_name'])[['id', 'Name', 'type', 'NAG']]

print(result)

运行后输出:

id Name type NAG
1  AAA    A   yy   B
2  AAA    A   xx   C
4  BBB    C   zz   D
5  BBB    C   yy   B

更优版实现(包含typeNAG列)

import pandas as pd

# 构造原始数据(如果已有DataFrame可跳过此步)
df = pd.DataFrame({
    'id': ['AAA', 'AAA', 'AAA', 'BBB', 'BBB', 'BBB'],
    'Name': ['A', 'B', 'C', 'C', 'D', 'B'],
    'type': ['xx', 'yy', 'xx', 'xx', 'zz', 'yy'],
    'start': ['yes', 'no', 'no', 'yes', 'no', 'no']
})

# 直接提取每组start为yes的行的Name和type,重命名为目标字段
grouped_target = df[df['start'] == 'yes'][['id', 'Name', 'type']].rename(
    columns={'Name': 'target_name', 'type': 'target_type'}
)

# 合并原始数据与目标字段
merged_df = df.merge(grouped_target, on='id')

# 处理start为no的行
result = merged_df[merged_df['start'] == 'no'].copy()
result['NAG'] = result['Name']  # 保存原Name
result['typeNAG'] = result['type']  # 保存原type
result['Name'] = result['target_name']  # 替换Name
result['type'] = result['target_type']  # 替换type

# 移除多余列并调整顺序
result = result.drop(columns=['start', 'target_name', 'target_type'])[
    ['id', 'Name', 'type', 'NAG', 'typeNAG']
]

print(result)

运行后输出:

id Name type NAG typeNAG
1  AAA    A   xx   B      yy
2  AAA    A   xx   C      xx
4  BBB    C   xx   D      zz
5  BBB    C   xx   B      yy

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:50:23