Python 如何向数据框中添加一列,其中包含来自另一个数据框的年份之间的平均值?
我有两个Python数据帧,一个包含汽车信息,另一个包含燃油价格(汽油和柴油)信息。数据帧的示例如下所示 汽车Python 如何向数据框中添加一列,其中包含来自另一个数据框的年份之间的平均值?,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个Python数据帧,一个包含汽车信息,另一个包含燃油价格(汽油和柴油)信息。数据帧的示例如下所示 汽车 regNo regYear inspectionYear fuelType 0 AB1234 2008 2012 Gasoline 1 CD2345 2009 2011 Diesel 2 LD9876 2010 2013 Diesel 燃料价格 year fuelType price 2008
regNo regYear inspectionYear fuelType
0 AB1234 2008 2012 Gasoline
1 CD2345 2009 2011 Diesel
2 LD9876 2010 2013 Diesel
燃料价格
year fuelType price
2008 Gasoline 12.13
2009 Gasoline 19.52
2010 Gasoline 13.32
2011 Gasoline 13.54
2012 Gasoline 16.23
2013 Gasoline 11.34
2008 Diesel 9.43
2009 Diesel 9.37
2010 Diesel 9.89
2011 Diesel 10.04
2012 Diesel 8.42
2013 Diesel 9.21
我试图做的是在cars中添加一列,这是regYear和inspectionYear之间相关燃料类型的平均价格。因此,我希望以这样的方式结束:
cars\u newCol
regNo regYear inspectionYear fuelType fuelPrice
0 AB1234 2008 2012 Gasoline 14.95
1 CD2345 2009 2011 Diesel 9.77
2 LD9876 2010 2013 Diesel 9.39
也就是说,第一行是2008年至2012年间汽油燃料价格的平均值
我尝试过各种解决方案,但我觉得最接近的可能是:
cars['fuelPrice'] = fuel_prices.loc[(fuel_prices['year']>=cars['regYear']) &
(fuel_prices['year']<=cars['inspectionYear']) &
(fuel_prices['fuelType']==cars['fuelType']),
'price'].mean()
cars['fuelPrice']=燃料价格。loc[(燃料价格['year']>=汽车['regYear'])和
(燃油价格['year']您需要合并
,然后筛选行和分组依据:
(cars.merge(fuelPrice, on='fuelType')
.query('regYear<= year <= inspectionYear')
.groupby(cars.columns.to_list(), as_index=False)['price'].mean()
)
regNo regYear inspectionYear fuelType price
0 AB1234 2008 2012 Gasoline 14.948000
1 CD2345 2009 2011 Diesel 9.766667
2 LD9876 2010 2013 Diesel 9.390000