根据另一个数据帧的范围从数据帧中选择最小值

问题描述 投票:1回答:1

我有一个数据帧qazxsw poi:

df1

我有另一个数据框Type StDt EnDt A 1/2/2012 1/4/2012 B 1/6/2012 1/6/2012 ,所有日期直到2019年:

df2

对于 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 中的每一行,我需要使用日期范围StDt,EnDt从df2中提取所有行并获取其最小值以获得以下内容:

df1

我不确定如何有效地做到这一点,因为数据帧很大。

python pandas dataframe intervals
1个回答
2
投票

初步准备:将所有相关列和指数转换为qazxsw poi。

Type    StDt    EnDt       Minimum
A   1/2/2012    1/4/2012   14.00
B   1/6/2012    1/6/2012   27.00

一个简单的方法是使用datetimedf[['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 (数字,单调增加)。

© www.soinside.com 2019 - 2024. All rights reserved.