如果在另一个df中的日期范围之间,python将值分配给pandas df


问题内容

如果日期在另一个数据框中的两个日期之间,则创建新列并分配值的最佳方法是什么?

例如

dataframe A    
date          values
2017-05-16      x  
2017-04-12      Y


dataframe B    #df contains dates to use to filter and associated id

start            end           id
2017-05-08     2017-05-18      34
2017-04-24     2017-05-08      33
2017-04-03     2017-04-24      32

理想的结果

dataframe A     
date          values    id
2017-05-16      x       34 
2017-04-12      Y       32

我研究了pd.cut,它似乎对我想要的东西都不起作用,并且编写循环以在多个条件下遍历数据帧似乎效率不高。


问题答案:

使用IntervalIndex,这是Pandas 0.20.0中的新功能。不过,这似乎仍处于实验阶段,因此其他解决方案可能更可靠。

# Get the 'id' column indexed by the 'start'/'end' intervals.
s = pd.Series(df_b['id'].values, pd.IntervalIndex.from_arrays(df_b['start'], df_b['end']))

# Map based on the date of df_a.
df_a['id'] = df_a['date'].map(s)

结果输出:

        date values  id
0 2017-05-16      x  34
1 2017-04-12      Y  32

另外,如果您不介意更改的索引df_b,则可以直接将IntervalIndex其转换为on:

# Create an IntervalIndex on df_b.
df_b = df_b.set_index(['start', 'end'])
df_b.index = pd.IntervalIndex.from_tuples(df_b.index)

# Map based on the date of df_a.
df_a['id'] = df_a['date'].map(df_b['id'])