0
我想分割一個Multiindex Dataframe。讓我們以一個例子這DF:在Pandas Multiindex上相交
import pandas as pd
arrays = [['bar', 'bar', 'bar','bar', 'foo','foo', 'qux', 'qux',
'qux','qux', 'qux'],
['2', '3', '4','10', '3','10','2','3','6','10','11']]
df = pd.DataFrame(np.random.randn(11, 4), index=arrays).sort_index()
- >
0 1 2 3
bar 10 1.411962 -0.742729 0.950159 1.074269
2 1.214804 -0.654806 -1.138855 0.609101
3 0.135363 1.226927 -0.501535 -0.791849
4 1.118516 -1.340844 -1.365790 -0.099575
foo 10 -0.004108 -0.067574 -0.139101 -0.358282
3 0.612849 -0.598579 0.923299 -0.218198
qux 10 0.112769 -1.330163 2.195480 -0.347462
11 0.057467 -0.204044 0.020474 -1.198299
2 1.011604 -0.411514 0.941112 -0.509703
3 0.524958 -0.855275 0.257481 0.630311
6 1.989778 -0.099014 0.302340 -0.067559
現在我想只是其中第二指標具有一定的值的行。因此,可以說我只是想排在第二索引中包含「2」和「3」和「10」,所以我可以做的:
sliced = df.loc[(slice(None), ['2','3','10']), :]
這將產生:
0 1 2 3
bar 10 1.411962 -0.742729 0.950159 1.074269
2 1.214804 -0.654806 -1.138855 0.609101
3 0.135363 1.226927 -0.501535 -0.791849
foo 10 -0.004108 -0.067574 -0.139101 -0.358282
3 0.612849 -0.598579 0.923299 -0.218198
qux 10 0.112769 -1.330163 2.195480 -0.347462
2 1.011604 -0.411514 0.941112 -0.509703
3 0.524958 -0.855275 0.257481 0.630311
,但我不想與['10','3']的行。所以期望的結果將是:
0 1 2 3
bar 10 1.411962 -0.742729 0.950159 1.074269
2 1.214804 -0.654806 -1.138855 0.609101
3 0.135363 1.226927 -0.501535 -0.791849
qux 10 0.112769 -1.330163 2.195480 -0.347462
2 1.011604 -0.411514 0.941112 -0.509703
3 0.524958 -0.855275 0.257481 0.630311
我試過,但我不能得到我的頭如何妥善解決這個問題。任何幫助是極大的讚賞。
不...不相信這是可能的通過切片。 –