假設我有以下數據框:索引數據幀後更新大熊貓多指標
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'])
這對正常的數據幀不會發生。如果您編制索引,剩餘的副本(甚至視圖)只包含選定的索引/列。這是煩人,因爲我可能會經常做很多的大dataframes過濾,並在結束時,我想通過只是在做
df.index
df
這也發生了多指標列知道還剩下什麼指標。是否有更新索引/列並刪除空條目的正確方法?
要清楚,我希望過濾的數據幀具有相同的結構(多索引索引和列)。例如,我想做的事:
temp = s.loc[(('bar', 'foo'), slice(None)), :]
但指數仍然有「巴茲」和「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'])
要清楚,我想看看效果,我寫了這snippet消除多餘條目:
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]])
我有這個確切的問題,我想你會發現Ezekiel Kruglick(在這個頁面上)的答案可以最好地解決你的問題。我添加了一個.unique()來刪除重複項:'df.index.get_level_values(some_level).unique()' –