这是我的数据框:
iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two', 'three', 'four']]
mindex = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(16, 3), index=mindex)
它看起来像这样:
0 1 2
first second
bar one -0.445212 -2.208192 -1.297759
two 1.521942 0.592622 -1.677931
three 0.709292 0.348715 -0.766430
four -1.812516 -0.982077 -1.155860
baz one -0.375230 -0.267912 2.621249
two -1.041991 -0.752277 -0.494512
three -1.029389 -0.331234 0.950335
four -1.357269 0.653581 1.289331
foo one 0.980196 0.865067 -0.780575
two -1.641748 0.220253 2.141745
three 0.272158 -0.320238 0.787176
four -0.265425 -0.767928 0.695651
qux one -0.117099 1.089503 -0.692016
two -0.203240 -0.314236 0.010321
three 1.425749 0.268420 -0.886384
four 0.181717 -0.268686 1.186988
我想为第一个索引中的每个元素选择数据帧的子集,以便仅使用来自多索引的第二级的一个和三个索引值.
我已经检查了in the advanced indexing section的文档,但没有太大的成功.可以从第二个索引级别中选择一个特定的索引值:
df.loc['bar','one']
Out[74]:
0 -0.445212
1 -2.208192
2 -1.297759
Name: (bar, one), dtype: float64
但不是一个价值元组,因为这:
df.loc[('bar',('one','three'))]
导致错误:
KeyError: “None of [(‘one’, ‘three’)] are in the [columns]”
我希望.loc基本上通过这个命令传递bar,然后是第二级索引值为1和3的行.
如何基于多索引级别子集执行此类子选择?
解决方法:
添加:用于选择所有列:
a = df.loc[('bar',('one','three')), :]
print (a)
0 1 2
first second
bar one -0.902444 2.115037 -0.065644
three 2.095998 0.768128 0.413566
与IndexSlice类似的解决方案:
idx = pd.IndexSlice
a = df.loc[idx['bar', ('one','three')], :]
print (a)
0 1 2
first second
bar one -0.515183 -0.858751 0.854838
three 2.315598 0.402738 -0.184113
正如@Brad所罗门所提到的,如果想要所有第一级的价值:
df1 = df.loc[(slice(None), ['one', 'three']), :]
idx = pd.IndexSlice
df1 = df.loc[idx[:, ('one','three')], :]
print (df1)
0 1 2
first second
bar one -0.266926 1.105319 1.768572
three -0.632492 -1.642508 -0.779770
baz one -0.380545 -1.632120 0.435597
three 0.018085 2.114032 0.888008
foo one 0.539179 0.164681 1.598194
three 0.051494 0.872987 -1.882287
qux one -1.361244 -1.520816 2.678428
three 0.323771 -1.691334 -1.826938
标签:python,pandas,multi-index 来源: https://codeday.me/bug/20190527/1161872.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。