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

如何为Pandas DataFrame添加对应Name出现次数的Price列

解决方案:为分组后的Pandas DataFrame添加历史价格列

完整实现代码

import pandas as pd

# 构造示例数据(替换为你的实际DataFrame)
data = {
    'Name': ['a', 'a', 'a', 'b', 'b', 'c'],
    'Year': [2019, 2020, 2021, 2015, 2019, 2011],
    'Price': [10, 20, 30, 55, 75, 15]
}
df = pd.DataFrame(data)

# 获取每个Name的最大出现次数
max_occurrences = df['Name'].value_counts().max()

# 生成Price_2到Price_{max_occurrences}列
for i in range(2, max_occurrences + 1):
    # 移位i-1位后向前填充,确保历史值能传递到后续行
    df[f'Price_{i}'] = df.groupby('Name')['Price'].shift(i-1).ffill()

# 将空值填充为0,并转换为整数类型(匹配原Price格式)
df = df.fillna(0).astype({col: int for col in df.columns if col.startswith('Price_')})

print(df)

代码说明

  1. 分组移位:通过groupby('Name')['Price'].shift(i-1),按Name分组后将Price列向上移动i-1行,这样第n行的Price_i会对应同组内第n-(i-1)行的原始Price值。
  2. 向前填充:.ffill()用于补全移位后出现的空值,比如第三个a的Price_2需要继承第一个a的Price值,通过向前填充实现值的传递。
  3. 空值补0:fillna(0)将每组前i-1行没有历史值的位置填充为0,符合需求格式。
  4. 类型统一:最后转换为整数类型,保证新列和原Price列的数据格式一致。

输出结果

NameYearPricePrice_2Price_3
a20191000
a202020100
a2021301020
b20155500
b201975550
c20111500

如果你的数据中Name的最大出现次数为4,代码会自动生成Price_2、Price_3、Price_4三列,无需手动修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 18:05:32