python - Pandas 索引缺失值

标签 python pandas time-series missing-data

假设我有以下 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/

相关文章:

r - 将分析权重应用于时间序列数据

r - 通过 R 中的 xts 进行动态周期子集化

python - 使用 altinstall 创建 virtualenv

python - python中图像数组的居中

python - 如何将数据分组到1度纬度的箱中?

python - 有没有办法将 python pandas 数据框转换为 NLP 语料库或文档?

php - 检测时间序列中满足特定条件的连续项目

python - mpz 变量的算术结果是什么?

python - 如何使用 Anaconda 的解释器设置 SublimeREPL?

python - 如何通过检查条件来替换数据框中的值?