熊猫索引缺失值

时间:2018-08-16 15:17:31

标签: python pandas time-series missing-data

假设我有以下两个数据框:

我有一个时间序列,其中包含不同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。

是否有更好,更快的方法来达到相同的结果? 预先感谢!

1 个答案:

答案 0 :(得分:2)

在用factor颠倒顺序之后,您可以在列[::-1]transform上使用cumprod,全部在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