python - 尝试使用一个数据帧的元素来完成 2 个数据帧的最小值

标签 python pandas dataframe merge

我有两个 DataFrame,我试图根据另一个 DataFrame 中的值来完成其中一个的最小值,这是一个示例:

aggDF

一些日期,一些Val

1/1/2010 5
1/1/2011 6
1/1/2012 7
1/1/2013 8

currDF

其他日期

1/1/2009
1/1/2010
6/1/2010

所需的outputDF(日期不是非常重要,如果我只得到 myVal 就可以了):

otherDate myVal

1/1/2009 5
1/1/2010 5
6/1/2010 6

我觉得我现在的做法太复杂/太慢:

outputDF = [aggDF[aggDF.someDate >= currDate] for currDate in currDF.otherDate]
outputDF = [outputDF[i]['someVal'] for i in range(0, len(outputDF)]
outputDF = [outputDF[i].iloc[0] for i in range(0, len(outputDF)]

当然有更好的方法来完成我想做的事情。我将不胜感激任何帮助,谢谢

最佳答案

所以我相信merge_asof这就是您正在寻找的。这是给出您想要的输出的示例。

aggdf = pd.DataFrame({'someDate': ['1/1/2010', '1/1/2011',
                                   '1/1/2012', '1/1/2013'],
                      'someVal': [5,6,7,8]})

currdf = pd.DataFrame({'otherDate': ['1/1/2009', '1/1/2010',
                                     '6/1/2010']})

aggdf['someDate'] = pd.to_datetime(aggdf['someDate'])
currdf['otherDate'] = pd.to_datetime(currdf['otherDate'])

pd.merge_asof(currdf, aggdf, direction='forward',
              left_on='otherDate', right_on='someDate')

输出:

    otherDate   someDate    someVal
0   2009-01-01  2010-01-01  5
1   2010-01-01  2010-01-01  5
2   2010-06-01  2011-01-01  6

关于python - 尝试使用一个数据帧的元素来完成 2 个数据帧的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59462969/

相关文章:

python - 根据唯一/重复索引值将 Pandas DataFrame 重新组织为更多列

Python Pandas数据帧分割错误: operation not ' ' safe' '

数据框中的 Pandas 聚合计数

python - 匹配冒号前后的单词

python - 如何将行转置为 Pandas 中的列?

Python:在文件中寻找相同的词?

python - 使用python只读excel中的可见行

python - 每天重新采样到每月一次,并在 pandas 中偏移 'month-end minus t days'

python - 检查一个 numpy 数组中有多少个 numpy 数组与另一个不同大小的 numpy 数组中的其他 numpy 数组相等

python - 如何在concurrent.futures.ThreadPoolExecutor中使用锁而不导致死锁?