首先,出现该警告的原因是因为我们在使用.loc或[]时传递了一个缺失标签的列表。一种解决该问题的方法是将列表转换为一个完整的索引。
例如,假设我们有一个DataFrame df,并且我们想要选择具有以下标签的行:['a', 'b', 'c', 'd', 'e']。
旧方法:
df.loc[['a', 'c', 'e', 'f']]
新方法:
df.reindex(['a', 'b', 'c', 'd', 'e']).loc[['a', 'c', 'e', 'f']]
在新方法中,我们首先使用reindex方法将索引转换为完整的索引,然后再使用.loc方法选择具有特定标签的行。
如果我们只需要选择现有索引中存在的标签,则可以使用intersection方法:
df.loc[df.index.intersection(['a', 'c', 'e', 'f'])]