Python Pandas Select index其中index大于x

use*_*887 16 python indexing conditional-statements pandas

假设我有一个DataFrame df,日期作为索引和一些值.如何选择日期大于某个值的行x

我知道我可以将索引转换为列然后执行select df[df['date']>x],但是比在索引上执行操作要慢吗?

Dat*_*eek 22

使用索引从DataFrame中选择的示例:

from numpy.random import randn
from pandas import DataFrame
from datetime import timedelta as td
import dateutil.parser

d = dateutil.parser.parse("2014-01-01")
df = DataFrame(randn(6,2), columns=list('AB'), index=[d + td(days=x) for x in range(1,7)])

In [1]: df
Out[1]:
                   A         B
2014-01-02 -1.172285  1.706200
2014-01-03  0.039511 -0.320798
2014-01-04 -0.192179 -0.539397
2014-01-05 -0.475917 -0.280055
2014-01-06  0.163376  1.124602
2014-01-07 -2.477812  0.656750

In [2]: df[df.index > dateutil.parser.parse("2014-01-04")]
Out[2]:
                   A         B
2014-01-05 -0.475917 -0.280055
2014-01-06  0.163376  1.124602
2014-01-07 -2.477812  0.656750
Run Code Online (Sandbox Code Playgroud)

  • 上面的答案更加稳健,但是如果您想获得快速查询(例如,使用 jupyter 笔记本时),以下内容也有效: df[de.index > "2014-01-04"] (2认同)

ntg*_*ntg 10

现有的答案是正确的,但是如果我们根据索引进行选择,那么这里的第二种方法会更快:

# Set index
df = df.set_index(df['date'])

# Select observations between two datetimes
df.loc[pd.Timestamp('2002-1-1 01:00:00'):pd.Timestamp('2002-1-1 04:00:00')]
Run Code Online (Sandbox Code Playgroud)