【发布时间】:2019-07-31 23:51:14
【问题描述】:
我在输入数据帧 (input_df) 中有数据。基于另一个基准数据帧(bm_df)中的索引,我想创建第三个数据帧(output_df),该数据帧是根据使用原始两个数据帧中的索引的条件填充的。
对于 bm_df 索引中的每个日期,我想使用 input_df 中可用的最新数据填充我的输出,条件是数据的索引日期早于或等于 bm_df 中的索引日期。例如,在案例研究中,第一个索引日期 (2019-01-21) 的输出数据框下方的数据将使用来自 2019-01-21 的 input_df 数据点的数据进行填充。但是,如果 2019-01-21 的数据点不存在,则将使用 2019-01-18。
此处的用例是映射和回填大型数据集以获取给定日期的最新可用数据。我已经编写了一些 python 来为我做这件事(这很有效),但是我认为可能有一种更 Pythonic 并且因此更快的方法来实现该解决方案。我应用的基础数据集在列数和列长度方面具有很大的维度,因此我想要尽可能高效的东西 - 我当前的解决方案在我正在使用的完整数据集上运行时太慢了。
非常感谢任何帮助!
输入_df:
index data
2019-01-21 0.008
2019-01-18 0.016
2019-01-17 0.006
2019-01-16 0.01
2019-01-15 0.013
2019-01-14 0.017
2019-01-11 0.017
2019-01-10 0.024
2019-01-09 0.032
2019-01-08 0.012
bm_df:
index
2019-01-21
2019-01-14
2019-01-07
输出_df:
index data
2019-01-21 0.008
2019-01-14 0.017
2019-01-07 NaN
请看下面我目前使用的代码:
import pandas as pd
import numpy as np
# Import datasets
test_index = ['2019-01-21','2019-01-18','2019-01-17','2019-01-16','2019-01-15','2019-01-14','2019-01-11','2019-01-10','2019-01-09','2019-01-08']
test_data = [0.008, 0.016,0.006,0.01,0.013,0.017,0.017,0.024,0.032,0.012]
input_df= pd.DataFrame(test_data,columns=['data'], index=test_index)
test_index_2= ['2019-01-21','2019-01-14','2019-01-07']
bm_df= pd.DataFrame(index=test_index_2)
#Preallocate
data_mat= np.zeros([len(bm_df)])
#Loop over bm_df index and find the most recent variable from input_df which from a date before the index date
for i in range(len(bm_df)):
#First check to see if there are no dates before the selected date, if true fill with NaN
if sum(input_df.index <= bm_df.index[i])>0:
data_mat[i] = input_df['data'][max(input_df.index[input_df.index <= bm_df.index[i]])]
else:
data_mat[i] = float('NaN')
output_df= pd.DataFrame(data_mat,columns=['data'],index=bm_df.index)
【问题讨论】:
标签: python loops dataframe indexing