Python 为什么多索引数据帧在选择后会返回所有索引?
我发现多索引数据帧有一点非常奇怪: 对于非常简单的df:Python 为什么多索引数据帧在选择后会返回所有索引?,python,pandas,multi-index,Python,Pandas,Multi Index,我发现多索引数据帧有一点非常奇怪: 对于非常简单的df: import pandas as pd df = pd.DataFrame([{'Name': 'Chris', 'Item Purchased': 'Sponge', 'Cost': 22.50}, {'Name': 'Kevyn', 'Item Purchased': 'Kitty Litter', 'Cost': 2.50}, {'Name': 'Filip', 'Item Purchased': 'Spoon', 'Cost
import pandas as pd
df = pd.DataFrame([{'Name': 'Chris', 'Item Purchased': 'Sponge', 'Cost': 22.50},
{'Name': 'Kevyn', 'Item Purchased': 'Kitty Litter', 'Cost': 2.50},
{'Name': 'Filip', 'Item Purchased': 'Spoon', 'Cost': 5.00}],
index=['Store 1', 'Store 2', 'Store 3'])
df3 = df.reset_index()
df3 = df3.set_index(['index', 'Name'])
如果我只想得到大于4美元的指数。很容易选择:
df4 = df3[df3['Cost'] > 4]
df4
但当我尝试从索引中获取存储id时:
df4.index.levels[0]
应仅为存储1和存储3,但实际结果:
Index(['Store 1', 'Store 2', 'Store 3'], dtype='object', name='index')
所以,看起来索引仍然会返回原始索引中的所有成员,即使在选择之后也是如此
有人能告诉我为什么会发生这种情况,以及如何在选择后获得正确的索引吗
谢谢。使用:
使用:
df4.index = df4.index.remove_unused_levels()
print (df4.index.levels[0])