如果日期介于另一个数据框中的两个日期之间,那么创建新列并赋值的最佳方法是什么?
例如
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,它似乎无法满足我的需求,并且编写循环以在多个条件下迭代数据帧似乎效率低下。
最佳答案
使用 Pandas 0.20.0 中新增的 IntervalIndex
。不过,这看起来仍处于试验阶段,因此其他解决方案可能更可靠。
# 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
:
# 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'])
关于如果落在另一个 df 的日期范围之间,python 将值分配给 pandas df,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44053666/