pandas如何按条件为现有DataFrame新增last_year_price列
pandas新增同水果上一年价格列实现方案
方法1:分组移位法(适合年份连续无断档场景,性能最优)
- 核心逻辑:先按水果分组、组内按年份升序排序,再对价格列做向下移位1位,直接取同组上一行的价格作为上一年价格
- 实现代码:
import pandas as pd # 构造示例DataFrame df = pd.DataFrame({ 'fruit': ['apple', 'apple', 'apple', 'plum', 'plum'], 'year': [2018, 2019, 2020, 2019, 2020], 'price': [4, 3, 5, 3, 2] }) # 必须先按水果、年份排序,避免原表顺序错乱导致匹配错误 df = df.sort_values(by=['fruit', 'year']).reset_index(drop=True) # 分组移位生成新列 df['last_year_price'] = df.groupby('fruit')['price'].shift(1)
- 运行后结果:
| fruit | year | price | last_year_price |
|---|---|---|---|
| apple | 2018 | 4 | NaN |
| apple | 2019 | 3 | 4.0 |
| apple | 2020 | 5 | 3.0 |
| plum | 2019 | 3 | NaN |
| plum | 2020 | 2 | 3.0 |
方法2:表连接匹配法(适合存在年份断档场景,匹配更严谨)
- 核心逻辑:如果数据存在年份缺失(比如某水果没有2019年数据,直接从2018跳到2020),移位法会错误把2018年价格匹配给2020年,此时用左连接精准匹配「同水果、年份差为1」的价格即可避免错配
- 实现代码:
# 生成上一年价格对照表:年份+1后,原年份就对应当前年份的上一年 last_year_map = df[['fruit', 'year', 'price']].rename(columns={'price': 'last_year_price'}) last_year_map['year'] += 1 # 左连接匹配上一年价格 df = df.merge(last_year_map, on=['fruit', 'year'], how='left')
- 该方法不管年份是否连续,都能精准匹配到严格对应上一年的价格,无匹配数据时返回
NaN,容错性更强。
内容的提问来源于stack exchange,提问作者gaba42
相关产品推荐
相关产品推荐

