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
相关产品推荐
相关产品推荐

