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

如何按DataFrame中A列关键日期将C列0值替换为对应非0值?

解决方案

首先,你的原始DataFrame定义如下:

import pandas as pd

df = pd.DataFrame({'A': ['2022-09-09', '2022-09-12', '2022-09-12', '2022-09-12', '2022-09-13'],
                  'B' : ['2022-09-01', '2022-09-02', '2022-09-03', '2022-09-04', '2022-09-05'],
                  'C' : [4701.80, 0, 12571.13, 0, 3011.06]})

要实现按A列日期替换C列的0值,核心思路是按A列分组,提取每组内的非0值,再用该值替换组内的0。这里假设每个A日期对应的组里只有一个非0值(如示例中的情况),可以用以下两种简洁方法:

方法1:groupby + transform 自定义逻辑

# 按A列分组,对每组C列的0值替换为组内的非0值
df['C'] = df.groupby('A')['C'].transform(lambda x: x.replace(0, x[x != 0].iloc[0]))

方法2:mask + groupby 取首个有效值

因为每组非0值唯一,first()会直接获取到该值:

# 当C列为0时,用对应A组的首个非0值替换
df['C'] = df['C'].mask(df['C'] == 0, df.groupby('A')['C'].transform('first'))

执行后得到的目标结果:

ABC
2022-09-092022-09-014701.80
2022-09-122022-09-0212571.13
2022-09-122022-09-0312571.13
2022-09-122022-09-0412571.13
2022-09-132022-09-053011.06

补充说明

如果某个A组存在多个非0值,可根据需求修改替换规则:

  • 取组内非0值的均值:lambda x: x.replace(0, x[x != 0].mean())
  • 取组内非0值的最大值:lambda x: x.replace(0, x[x != 0].max())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:01:22