如何使用Python Pandas在特定日期时间索引之后获取最接近的单行 [英] How to get the closest single row after a specific datetime index using Python Pandas
本文介绍了如何使用Python Pandas在特定日期时间索引之后获取最接近的单行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我拥有的DataFrame:
DataFrame I have:
A B C
2012-01-01 1 2 3
2012-01-05 4 5 6
2012-01-10 7 8 9
2012-01-15 10 11 12
我现在正在使用什么:
date_after = dt.datetime( 2012, 1, 7 )
frame.ix[date_after:].ix[0:1]
Out[1]:
A B C
2012-01-10 7 8 9
还有更好的方法吗?我不喜欢我必须指定.ix [0:1]而不是.ix [0],但是如果不这样做,输出将更改为TimeSeries,而不是DataFrame中的单行.我发现更难在原始DataFrame的顶部使用旋转的TimeSeries.
Is there any better way of doing this? I do not like that I have to specify .ix[0:1] instead of .ix[0], but if I don't the output changes to a TimeSeries instead of a single row in a DataFrame. I find it harder to work with a rotated TimeSeries back on top of the original DataFrame.
没有.ix[0:1]
:
frame.ix[date_after:].ix[0]
Out[1]:
A 7
B 8
C 9
Name: 2012-01-10 00:00:00
谢谢
约翰
推荐答案
您可能想直接进行索引:
You might want to go directly do the index:
i = frame.index.searchsorted(date)
frame.ix[frame.index[i]]
冗长的触摸,但您可以将其放在函数中.大约和你会得到的一样(O(log n)
)
A touch verbose but you could put it in a function. About as good as you'll get (O(log n)
)
这篇关于如何使用Python Pandas在特定日期时间索引之后获取最接近的单行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文