1、场景
1)有名字为 df 的 dataframe,行索引是时间,列索引是资产代码。
from pandas import DataFrame
from numpy import random
from datetime import datetime, timedelta
begin_datetime = datetime(2000, 1, 1, 9, 30, 00)
ts_lst = ts_lst = [b + timedelta(minutes=ii) for ii in range(10000)]
df = pd.DataFrame(index=ts_lst, data={'d1': np.random.randint(low=-1000, high=1000, size=10000), 'd2': np.random.randint(low=-1000, high=1000, size=10000)}) / 100
2)想知道某个资产在某个时间上是否有数据。
2、解决方案
In [22]: '2000-01-01 11:30' in df.index
Out[22]: True
In [23]: 4.3 in df.d1.values
Out[23]: True
效率情况:
In [21]: df2 = df.copy()
In [22]: df2 = df2.set_index('d1')
In [24]: %timeit ([ii in df.d1.values for ii in nums])
40.3 ms ± 383 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [27]: %timeit ([ii in df2.index for ii in nums])
5.81 ms ± 60.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
可以看出,直接对一列的值进行判断,比对行索引进行判断要慢得多。
因此,从效率的角度出发,如果想快速判断某个值是否在 dataframe 中,能通过行、列索引来判断更好一些。
补充:对于多索引的检查,语法是
df = pd.DataFrame({'col1': ['a', 'b','c', 'd'], 'col2': ['X','X','Y', 'Y'], 'col3': [1, 2, 3, 4]}, columns=['col1', 'col2', 'col3'])
df = df.set_index(['col1', 'col2'])
'a' in df.index.levels[0] # True
'X' in df.index.levels[1] # True
或者:
('a', 'X') in df.index # True
('a', 'Y') in df.index # False