In a multi index
我想访问 pandas 数据框last第一个索引的所有值的第二个索引的元素。第二索引中的级别数根据第一索引的值而变化。我经历了pandas 多索引文档 http://pandas.pydata.org/pandas-docs/stable/advanced.html但找不到任何可以做到这一点的东西。
例如,对于下面的数据框:
arrays = [ ['bar', 'bar', 'baz', 'foo', 'foo', 'foo', 'qux'],
['one', 'two', 'one', 'one', 'two', 'three', 'one']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(7, 3), index=index, columns=['A', 'B', 'C'])
df
A B C
first second
bar one 0.289163 -0.464633 -0.060487
two 0.224442 0.177609 2.156436
baz one -0.262329 -0.248384 0.925580
foo one 0.051350 0.452014 0.206809
two 2.757255 -0.739196 0.183735
three -0.064909 -0.963130 1.364771
qux one -1.330857 1.881588 -0.262170
我想得到:
A B C
first second
bar two 0.224442 0.177609 2.156436
baz one -0.262329 -0.248384 0.925580
foo three -0.064909 -0.963130 1.364771
qux one -1.330857 1.881588 -0.262170
The dataframes
我正在与有超过10M
行,所以我想避免显式循环。