Pandas:最大的指数小于d

2024-06-02 08:42:07 发布

您现在位置:Python中文网/ 问答频道 /正文

给出以下示例性熊猫DataFramex

             a    b
2014-08-07   0.1  2.0
2014-08-18   0.2  4.0
2014-12-16   0.3  0.0
2015-01-16   0.4  2.3
2015-02-16   0.5  2.1
2015-03-18   0.6  7.0

索引属于datetime.date类型。在

我想写一个函数,它接受start类型的参数start,这样它就给了我一个比start更小的最大索引。在

例如,对于start = datetime.datetime(2015, 1, 20, 17, 30),小于start的最大索引是2015-01-16。在

这将给出a和{}中最新的变化,即{}。在


Tags: 函数示例类型参数datetimedatestartdataframex
3条回答

这是我使用TimeSeries的解决方案,但是对于DataFrame是相同的。在

基本上它在df上迭代,每次迭代检查日期是否大于“start”,如果不将刚刚检查的日期保存为“previous”,如果是,那么“previous”就是您的结果。在

import pandas as pd
import datetime

df = pd.TimeSeries({'2014-08-07': ['0.1', '2.0'],
                    '2014-08-18': ['0.2', '4.0'],
                    '2014-12-16': ['0.3', '0.0'],
                    '2015-01-16': ['0.4', '2.3'],
                    '2015-02-16': ['0.5', '2.1'],
                    '2015-03-18': ['0.6', '7.0']})

start = datetime.datetime(2015, 1, 20, 17, 30)
result = False
previous_i = False

for i,row in df.iteritems():
    if pd.to_datetime(i) >= start:
        result = previous_i
        break # you don't need to check further
    else:
        previous_i = i

print(result)


>>> 2015-01-16

测试解决方案:

Out[4]: 
              a    b
2014-08-07  0.1  2.0
2014-08-18  0.2  4.0
2014-12-16  0.3  0.0
2015-01-16  0.4  2.3
2015-02-16  0.5  2.1
2015-03-18  0.6  7.0

In [5]: %timeit df[df.index < pd.to_datetime("2015-09-01")].ix[-1, :]
The slowest run took 5.15 times longer than the fastest. This could mean that an intermediate result is being cached 
1000 loops, best of 3: 620 µs per loop

In [6]: %timeit df.iloc[:df.index.values.searchsorted(np.datetime64("2015-09-01"))].ix[-1, :]
The slowest run took 5.53 times longer than the fastest. This could mean that an intermediate result is being cached 
1000 loops, best of 3: 293 µs per loop

In [7]: %timeit df[:pd.to_datetime("2015-09-01")].ix[-1, :]
The slowest run took 5.66 times longer than the fastest. This could mean that an intermediate result is being cached 
1000 loops, best of 3: 450 µs per loop

__main__:6: FutureWarning: TimeSeries is deprecated. Please use Series
In [10]: %timeit alecsolution(df)
1000 loops, best of 3: 503 µs per loop

我认为最快的是:

^{pr2}$

pandas asof函数用于:

x.index.asof(start)

它可以用于序列索引或日期时间索引。在

参见:

http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DatetimeIndex.asof.html

相关问题 更多 >