如何为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)
代码说明
- 分组移位:通过
groupby('Name')['Price'].shift(i-1),按Name分组后将Price列向上移动i-1行,这样第n行的Price_i会对应同组内第n-(i-1)行的原始Price值。 - 向前填充:
.ffill()用于补全移位后出现的空值,比如第三个a的Price_2需要继承第一个a的Price值,通过向前填充实现值的传递。 - 空值补0:
fillna(0)将每组前i-1行没有历史值的位置填充为0,符合需求格式。 - 类型统一:最后转换为整数类型,保证新列和原Price列的数据格式一致。
输出结果
| Name | Year | Price | Price_2 | Price_3 |
|---|---|---|---|---|
| a | 2019 | 10 | 0 | 0 |
| a | 2020 | 20 | 10 | 0 |
| a | 2021 | 30 | 10 | 20 |
| b | 2015 | 55 | 0 | 0 |
| b | 2019 | 75 | 55 | 0 |
| c | 2011 | 15 | 0 | 0 |
如果你的数据中Name的最大出现次数为4,代码会自动生成Price_2、Price_3、Price_4三列,无需手动修改。
内容的提问来源于stack exchange,提问作者Gabriel Garcia
相关产品推荐
相关产品推荐

