我有两个 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/