假设我有以下 2 个数据框:
其中我有一个时间序列,其中包含不同 ID 的缺失价格值(“val”列):
import pandas as pd
df1 = pd.DataFrame({'id': ['1', '1', '1', '2', '2'],
'year': [2013, 2014, 2015, 2012, 2013],
'val': [np.nan, np.nan, 300, np.nan, 150]})
df1
看起来像:
id year val
0 1 2013 NaN
1 1 2014 NaN
2 1 2015 300.0
3 2 2012 NaN
4 2 2013 150.0
我有一个随时间变化的价格指数系列,我可以计算不同年份之间的价格通胀因素:
df2 = pd.DataFrame({'year': [2011, 2012, 2013, 2014, 2015],
'index': [100, 103, 105, 109, 115]})
df2['factor'] = df2['index'] / df2['index'].shift()
df2
看起来像:
year index factor
0 2011 100 NaN
1 2012 103 1.030000
2 2013 105 1.019417
3 2014 109 1.038095
4 2015 115 1.055046
现在假设我想使用第二个数据帧的因子对给定 id(商品)的最新可用价格值进行反向索引。哪种方法最有效?
到目前为止,我尝试了以下操作(但是对于我使用的大型数据集来说,这个循环非常慢,因为它只为每个循环填充 1 个时间段):
df1 = df1.merge(df2[['year', 'factor']], how = 'left', on = 'year')
missings = df1['val'].sum()
while df1['val'].isnull().sum() < missings:
missings = df1['val'].isnull().sum()
df1.loc[df1['val'].notnull(), 'factor'] = 1
df1['val'] = df1.groupby('id')['val'].fillna(method='bfill', limit=1)
df1['val'] = df1['val'] / df1['factor']
df1.drop(columns = 'factor').head()
这会产生以下结果:
id year val
0 1 2013 283.486239
1 1 2014 288.990826
2 1 2015 300.000000
3 2 2012 145.631068
4 2 2013 150.000000
因此 2014 年的值:300/1.038095。 2013 年的值:300/1.038095/1.019417。
有没有更好更快的方法来达到相同的结果? 提前致谢!
最佳答案
您可以使用transform
在因子
列和cumprod
上使用 [::-1]
反转顺序后,全部在 groupby
中,例如:
df1 = df1.merge(df2[['year', 'factor']], how = 'left', on = 'year')
df1.loc[df1['val'].notnull(),'factor']=1 #set factor to one where val exists
# here is how to get the factor you want when it's not just before a value
df1['factor'] = df1.groupby('id')['factor'].transform(lambda x: x[::-1].cumprod()[::-1])
df1['val'] = df1['val'].bfill()/df1['factor'] #back fill val no limitation and divide by factor
print (df1)
id year val factor
0 1 2013 283.486239 1.058252 #here it's 1*1.038095*1.019417
1 1 2014 288.990826 1.038095 #here it's 1*1.038095
2 1 2015 300.000000 1.000000
3 2 2012 145.631068 1.030000 #here it's 1*1.03
4 2 2013 150.000000 1.000000
关于python - Pandas 索引缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51880405/