假设我有以下数据框:
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.DataFrame(np.random.randn(8, 2), index=index, columns=[0, 1])
s
0 1
first second
bar one -0.012581 1.421286
two -0.048482 -0.153656
baz one -2.616540 -1.368694
two -1.989319 1.627848
foo one -0.404563 -1.099314
two -2.006166 0.867398
qux one -0.843150 -1.045291
two 2.129620 -2.697217
我知道通过索引选择一个子数据框:
temp = s.loc[('bar', slice(None)), slice(None)].copy()
temp
0 1
first second
bar one -0.012581 1.421286
two -0.048482 -0.153656
但是,如果我查看索引,原始索引的值仍然出现:
temp.index
MultiIndex(levels=[[u'bar', u'baz', u'foo', u'qux'], [u'one', u'two']],
labels=[[0, 0], [0, 1]],
names=[u'first', u'second'])
普通数据帧不会发生这种情况。如果索引,则剩余的副本(甚至 View )仅包含选定的索引/列。这很烦人,因为我可能经常对大数据帧进行大量过滤,最后我想知道剩下的索引
df.index
df
这也适用于多索引列。是否有更新索引/列并删除空条目的正确方法?
明确地说,我希望过滤后的数据框具有相同的结构(多索引索引和列)。例如,我想做:
temp = s.loc[(('bar', 'foo'), slice(None)), :]
但索引仍然有 'baz' 和 'qux' 值:
MultiIndex(levels=[[u'bar', u'baz', u'foo', u'qux'], [u'one', u'two']],
labels=[[0, 0, 2, 2], [0, 1, 0, 1]],
names=[u'first', u'second'])
为了明确我希望看到的效果,我写了这个片段来消除冗余条目:
import pandas as pd
def update_multiindex(df):
if isinstance(df.columns, pd.MultiIndex):
new_df = {key: df.loc[:, key] for key in df.columns if not df.loc[:, key].empty}
new_df = pd.DataFrame(new_df)
else:
new_df = df.copy()
if isinstance(df.index, pd.MultiIndex):
new_df = {key: new_df.loc[key, :] for key in new_df.index if not new_df.loc[key, :].empty}
new_df = pd.DataFrame(new_df).T
return new_df
temp = update_multiindex(temp).index
temp
MultiIndex(levels=[[u'bar', u'foo'], [u'one', u'two']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]])
最佳答案
两点。首先,我认为你可能想做一些实际上对你不利的事情。我知道过滤后的索引中有很多多余的东西很烦人,但是如果您重建索引以排除丢失的分类值,那么您的新索引将彼此不兼容,并且与原始索引不兼容。
也就是说,我怀疑(但不知道)以这种方式使用的 MultiIndex
是建立在 CategoricalIndex
之上的,后者具有方法 remove_unused_levels() .它可能被 MultiIndex
包裹着,但我不知道,因为...
其次,MultiIndex
在 pandas API documentation 中明显缺失.我不使用 MultiIndex
,但您可以考虑在 GitHub 上查找和/或打开票证如果你经常使用它的话。除此之外,您可能必须通过 source code 进行 grunnel如果您想找到有关 MultiIndex
可用功能的确切信息。
关于python - 在索引数据帧后更新 Pandas MultiIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30941425/