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

Pandas编码求助:生成含价格差值的新DataFrame

Pandas提取指定年份价格并计算差值的实现代码

方法一:使用透视表(Pivot Table)

这种方法简洁高效,适合快速将年份维度的数据转为列:

import pandas as pd

# 构造输入数据集
input_data = {
    'item': ['a', 'a', 'a', 'b', 'b', 'b'],
    'year': [2000, 2001, 2002, 2000, 2001, 2002],
    'price': [10, 12, 15, 5, 5, 4]
}
df = pd.DataFrame(input_data)

# 生成透视表,提取2000、2002年价格
pivot_result = df.pivot(index='item', columns='year', values='price').reset_index()
# 重命名列名以匹配期望格式
pivot_result.rename(columns={2000: 'price in 2000', 2002: 'price in 2002'}, inplace=True)

# 计算价格差值
pivot_result['difference'] = pivot_result['price in 2002'] - pivot_result['price in 2000']

# 整理最终列顺序
final_df = pivot_result[['item', 'price in 2000', 'price in 2002', 'difference']]
print(final_df)

运行后输出结果完全匹配期望格式:

item  price in 2000  price in 2002  difference
0    a             10             15           5
1    b              5              4          -1

方法二:筛选后合并数据集

如果需要更灵活的筛选逻辑,可以先提取指定年份的数据再合并:

import pandas as pd

input_data = {
    'item': ['a', 'a', 'a', 'b', 'b', 'b'],
    'year': [2000, 2001, 2002, 2000, 2001, 2002],
    'price': [10, 12, 15, 5, 5, 4]
}
df = pd.DataFrame(input_data)

# 筛选2000年数据并处理列名
df_2000 = df[df['year'] == 2000].rename(columns={'price': 'price in 2000'}).drop('year', axis=1)
# 筛选2002年数据并处理列名
df_2002 = df[df['year'] == 2002].rename(columns={'price': 'price in 2002'}).drop('year', axis=1)

# 按item合并两个数据集
merged_df = pd.merge(df_2000, df_2002, on='item')
# 计算差值
merged_df['difference'] = merged_df['price in 2002'] - merged_df['price in 2000']

print(merged_df)

两种方法都能得到符合要求的结果,可根据实际数据集的规模和需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:22:59