我有一个多指标列数据框,看起来像这样:如何仅使用MultiIndex列从DataFrame中选择特定列?
# sample data
col = pd.MultiIndex.from_arrays([['one', 'one', 'one', 'two', 'two', 'two'],
['a', 'b', 'c', 'a', 'b', 'c']])
data = pd.DataFrame(np.random.randn(4, 6), columns=col)
data
什么是从第二级只选择特定的列(如['a', 'c']
,而不是一个区间)的合适的,简单的方法?
目前,我这样做是这样的:
import itertools
tuples = [i for i in itertools.product(['one', 'two'], ['a', 'c'])]
new_index = pd.MultiIndex.from_tuples(tuples)
print(new_index)
data.reindex_axis(new_index, axis=1)
它不觉得自己是一个很好的解决方案,但是,因为我已经出局itertools
,手工打造的又一多指标和然后reindex(和我的实际代码更混乱,因为列列表并不是很容易获取)。我很确定必须有一些ix
或xs
这样做,但我试过的一切都会导致错误。
您是否尝试过使用字典? – darmat
不,我没有。你的意思是更快地构建MultiIndex?如果是这样,那不是重点 - 我想避免它,并直接用像'data.xs(['a','c'],axis = 1,level = 1)'这样的东西编号' – metakermit
让我们假设: – darmat