【发布时间】:2018-08-16 15:17:31
【问题描述】:
假设我有以下 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。
有没有更好更快的方法来达到同样的效果? 提前致谢!
【问题讨论】:
-
那么什么是val?
-
您可以尝试在合并之前从第二个数据集中删除重复项。并设置选项以获取最后/第一个结果,具体取决于其索引方式
-
df2.drop_duplicates('year', keep='first', inplace=False)不知道我是否理解这个问题 -
@RushabhMehta val 是价值列,例如价格,对于较早的年份,价值缺失,需要根据最近可用的价格向后填充(针对通货膨胀进行校正)。
-
@Ben.T 不,我之间没有 nan 值,所以给定的解决方案适用于我的用例。
标签: python pandas time-series missing-data