我有一个 datafrme df1
为:
Type StDt EnDt
A 1/2/2012 1/4/2012
B 1/6/2012 1/6/2012
我有另一个数据框 df2
,其中 2019 年之前的所有日期为:
KBWI
Date
2012-01-02 45.00
2012-01-03 32.00
2012-01-04 14.00
2012-01-05 26.00
2012-01-06 27.00
对于 df1 中的每一行,我需要使用日期范围 StDt、EnDt 从 df2 中提取所有行,并取其最小值以获得以下结果:
Type StDt EnDt Minimum
A 1/2/2012 1/4/2012 14.00
B 1/6/2012 1/6/2012 27.00
由于数据帧很大,我不知道如何有效地做到这一点。
最佳答案
初步准备:将所有涉及的列和索引转换为日期时间
。
df[['StDt', 'EnDt']] = df[['StDt', 'EnDt']].apply(pd.to_datetime, errors='coerce')
df2.index = pd.to_datetime(df2.index, errors='coerce')
df
Type StDt EnDt
0 A 2012-01-02 2012-01-04
1 B 2012-01-06 2012-01-06
df2
KBWI
Date
2012-01-02 45.0
2012-01-03 32.0
2012-01-04 14.0
2012-01-05 26.0
2012-01-06 27.0
一种简单的方法是使用 pd.IntervalIndex
和 groupby
来查找最小值:
idx = pd.IntervalIndex.from_arrays(df['StDt'], df['EnDt'], closed='both')
df['Minimum'] = df2['KBWI'].groupby(idx.get_indexer_non_unique(df2.index)).min()
df
Type StDt EnDt Minimum
0 A 2012-01-02 2012-01-04 14.0
1 B 2012-01-06 2012-01-06 27.0
假设df
的索引也是一个RangeIndex
(数字,单调递增),这是可行的。
关于python - 根据另一个数据帧的范围从数据帧中选择最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54449399/