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

基于条件用同Pandas DataFrame内其他行值替换指定行c1列值

Pandas列值替换实现方案

核心逻辑

  • 先按用户维度聚合,提取每个用户下VTX1字段为1时对应的c1值,生成映射字典
  • 匹配所有date与x值相等的行,将这些行的c1值替换为映射字典中对应用户的取值

实现代码

import pandas as pd

# 原始数据集
df = pd.DataFrame( {'user': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 2}, 
    'date': {0: '1995-09-01', 1: '1995-09-02', 2: '1995-10-03', 3: '1995-10-04', 4: '1995-10-05', 5: '1995-11-07', 6: '1995-11-08'}, 
    'x': {0: '1995-09-02', 1: '1995-09-02', 2: '1995-09-02', 3: '1995-10-05', 4: '1995-10-05', 5: '1995-10-05', 6: '1995-10-05'}, 
    'y': {0: '1995-10-03', 1: '1995-10-03', 2: '1995-10-03', 3: '1995-11-08', 4: '1995-11-08', 5: '1995-11-08', 6: '1995-11-08'}, 
    'c1': {0: '1', 1: '0', 2: '0', 3: '2', 4: '0', 5: '9', 6: '0'}, 
    'c2': {0: '1', 1: '0', 2: '0', 3: '2', 4: '0', 5: '9', 6: '0'}, 
    'c3': {0: '1', 1: '0', 2: '0', 3: '2', 4: '0', 5: '9', 6: '0'}, 
    'VTX1': {0: 1, 1: 0, 2: 0, 3: 1, 4: 0, 5: 0, 6: 0}, 
    'VTY1': {0: 0, 1: 1, 2: 0, 3: 0, 4: 0, 5: 1, 6: 0}} )

# 构建用户到目标c1值的映射
user_c1_map = df[df['VTX1'] == 1].groupby('user')['c1'].first().to_dict()
# 替换符合条件行的c1值
df.loc[df['date'] == df['x'], 'c1'] = df.loc[df['date'] == df['x'], 'user'].map(user_c1_map)

# 打印结果
print(df)

最终输出结果

user        date           x           y c1 c2 c3  VTX1  VTY1
0     1  1995-09-01  1995-09-02  1995-10-03  1  1  1     1     0
1     1  1995-09-02  1995-09-02  1995-10-03  1  0  0     0     1
2     1  1995-10-03  1995-09-02  1995-10-03  0  0  0     0     0
3     2  1995-10-04  1995-10-05  1995-11-08  2  2  2     1     0
4     2  1995-10-05  1995-10-05  1995-11-08  2  0  0     0     0
5     2  1995-11-07  1995-10-05  1995-11-08  9  9  9     0     1
6     2  1995-11-08  1995-10-05  1995-11-08  0  0  0     0     0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:54:01