【发布时间】:2019-06-15 20:47:18
【问题描述】:
我正在使用df.loc[(key1, key2)] 索引一个大型多索引 Pandas df。有时我会得到一个系列(如预期的那样),但有时我会得到一个数据框。我正在尝试隔离导致后者的情况,但到目前为止,我所看到的只是它与获得PerformanceWarning: indexing past lexsort depth may impact performance 警告相关。
我想复制它以在此处发布,但我无法生成另一个给我同样警告的案例。这是我的尝试:
def random_dates(start, end, n=10):
start_u = start.value//10**9
end_u = end.value//10**9
return pd.to_datetime(np.random.randint(start_u, end_u, n), unit='s')
np.random.seed(0)
df = pd.DataFrame(np.random.random(3255000).reshape(465000,7)) # same shape as my data
df['date'] = random_dates(pd.to_datetime('1990-01-01'), pd.to_datetime('2018-01-01'), 465000)
df = df.set_index([0, 'date'])
df = df.sort_values(by=[3]) # unsort indices, just in case
df.index.lexsort_depth
> 0
df.index.is_monotonic
> False
df.loc[(0.9987185534991936, pd.to_datetime('2012-04-16 07:04:34'))]
# no warning
所以我的问题是:是什么导致了这个警告?如何人工诱导?
【问题讨论】:
-
你读过吗:pandas.pydata.org/pandas-docs/stable/… 只是检查
-
是的 - 我试图按索引取消排序,所以我按列排序
-
不管怎样,很明显索引没有排序——数字是随机生成的。