我有一个具有非唯一多重索引的数据框:
A B
L1 L2
7.0 7.0 -0.4 -0.1
8.0 5.0 -2.1 1.6
5.0 8.0 -1.8 -0.8
7.0 7.0 0.5 -1.2
NaN -1.1 -0.9
5.0 8.0 0.6 2.3
我想使用值元组选择一些行:
data = df.loc[(7, 7), :]
毫不奇怪,会触发警告:
PerformanceWarning: indexing past lexsort depth may impact performance.
我试图了解当前索引中的原因导致此警告。我在这里读过很多答案,有些与旧版本的 pandas 有关,其他有帮助。据我所知,警告是由两个属性引起的:
因此,我正在使用根据此堆栈上找到的答案设计的函数来处理数据帧索引:
def adjust_index(df):
df = df.sort_index() # sort index
levels = list(range(len(df.index.levels)))
df_idx = df.groupby(level=levels).cumcount() # unique index
df_adj = df.set_index(df_idx, append=True) # change index
df_adj = df_adj.reset_index(level=-1, drop=True) # drop sorting level
return df_adj
这不会消除警告。你能解释一下什么是错误的、无用的或缺失的吗?
其余代码:
import pandas as pd
from numpy import nan, random as npr
npr.seed(2)
# Dataframe with unsorted MultiIndex
def create_df():
n_rows = 6
data = npr.randn(n_rows, 2).round(1)
choices = [8, 7, 5, 7, 8, nan]
columns = ['A', 'B']
levels = ['L1', 'L2']
tuples = list(zip(npr.choice(choices, n_rows), npr.choice(choices, n_rows)))
index = pd.MultiIndex.from_tuples(tuples, names=levels)
df = pd.DataFrame(data, index=index, columns=columns)
return df
df = create_df()
df = adjust_index(df)
data = df.loc[(7, 7), :] # <-- triggers warning
我通过对索引进行排序并将
NaN
值放在第一位来消除警告:
df.sort_index(inplace=True, na_position="first")
data = df.loc[(7, 7), :]
print(data)
打印:
A B
L1 L2
7.0 7.0 -0.4 -0.1
7.0 0.5 -1.2
我认为问题在于索引中的
NaN
值。 Pandas 对于索引中的每个唯一值都有特殊的 index.codes
,并且 NaN
被编码为 -1
。因此,要排序索引,您必须在第一个位置上具有此 -1
值,因此 na_position="first"