Pyt*_*ner 5 python multidimensional-array dataframe pandas
我想用相同的索引调用那些行。
所以这是示例数据框,
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
df = pd.DataFrame(np.random.randn(8, 4), index=arrays)
In [16]: df
Out[16]:
0 1 2 3
bar one -0.424972 0.567020 0.276232 -1.087401
two -0.673690 0.113648 -1.478427 0.524988
baz one 0.404705 0.577046 -1.715002 -1.039268
two -0.370647 -1.157892 -1.344312 0.844885
foo one 1.075770 -0.109050 1.643563 -1.469388
two 0.357021 -0.674600 -1.776904 -0.968914
qux one -1.294524 0.413738 0.276662 -0.472035
two -0.013960 -0.362543 -0.006154 -0.923061
Run Code Online (Sandbox Code Playgroud)
我想选择
0 1 2 3
bar one -0.424972 0.567020 0.276232 -1.087401
baz one 0.404705 0.577046 -1.715002 -1.039268
foo one 1.075770 -0.109050 1.643563 -1.469388
qux one -1.294524 0.413738 0.276662 -0.472035
Run Code Online (Sandbox Code Playgroud)
甚至作为这种格式
0 1 2 3
one -0.424972 0.567020 0.276232 -1.087401
one 0.404705 0.577046 -1.715002 -1.039268
one 1.075770 -0.109050 1.643563 -1.469388
one -1.294524 0.413738 0.276662 -0.472035
Run Code Online (Sandbox Code Playgroud)
我试过了df['bar','one],它不起作用。我现在确定我应该如何访问多级索引。
您可以使用 MultiIndex 切片(使用slice(None)而不是冒号):
df = df.loc[(slice(None), 'one'), :]
Run Code Online (Sandbox Code Playgroud)
结果:
0 1 2 3
bar one -0.424972 0.567020 0.276232 -1.087401
baz one 0.404705 0.577046 -1.715002 -1.039268
foo one 1.075770 -0.109050 1.643563 -1.469388
qux one -1.294524 0.413738 0.276662 -0.472035
Run Code Online (Sandbox Code Playgroud)
最后你可以删除第一个索引列:
df.index = df.index.droplevel(0)
Run Code Online (Sandbox Code Playgroud)
结果:
0 1 2 3
one -0.424972 0.567020 0.276232 -1.087401
one 0.404705 0.577046 -1.715002 -1.039268
one 1.075770 -0.109050 1.643563 -1.469388
one -1.294524 0.413738 0.276662 -0.472035
Run Code Online (Sandbox Code Playgroud)
如果需要,请使用DataFrame.xs两个级别添加drop_level=False:
df1 = df.xs('one', level=1, drop_level=False)
print (df1)
bar one -0.424972 0.567020 0.276232 -1.087401
baz one 0.404705 0.577046 -1.715002 -1.039268
foo one 1.075770 -0.109050 1.643563 -1.469388
qux one -1.294524 0.413738 0.276662 -0.472035
Run Code Online (Sandbox Code Playgroud)
DataFrame.reset_index对于第二个,通过with删除第一级drop=True,因此可以通过标签选择DataFrame.loc:
df2 = df.reset_index(level=0, drop=True).loc['one']
#alternative
#df2 = df.xs('one', level=1, drop_level=False).reset_index(level=0, drop=True)
print (df2)
0 1 2 3
one -0.424972 0.567020 0.276232 -1.087401
one 0.404705 0.577046 -1.715002 -1.039268
one 1.075770 -0.109050 1.643563 -1.469388
one -1.294524 0.413738 0.276662 -0.472035
Run Code Online (Sandbox Code Playgroud)
更常见的是在没有重复级别的情况下使用xs- 因此在one删除此级别后选择:
df3 = df.xs('one', level=1)
print (df3)
0 1 2 3
bar -0.424972 0.567020 0.276232 -1.087401
baz 0.404705 0.577046 -1.715002 -1.039268
foo 1.075770 -0.109050 1.643563 -1.469388
qux -1.294524 0.413738 0.276662 -0.472035
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4195 次 |
| 最近记录: |