Wählen Sie eine Liste von Slices eines Pandas Multiindex/Multicolumn DataFrame ausPython

Python-Programme
Anonymous
 Wählen Sie eine Liste von Slices eines Pandas Multiindex/Multicolumn DataFrame aus

Post by Anonymous »

Angenommen, ich habe den folgenden mehrspaltigen Pandas DataFrame:

Code: Select all

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', ],
['one', 'two', 'one', 'two', 'one', 'two', ]]

tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 6), columns=arrays)

bar                 baz                 foo
one       two       one       two       one       two
0  1.018709  0.295048 -0.735014  1.478292 -0.410116 -0.744684
1  1.388296  0.019284 -1.298793  1.597739  0.044640 -0.040337
2 -0.151763 -0.424984 -1.322985 -0.350483  0.590343 -2.189122
3 -0.221250 -0.449578 -1.512640  0.077380 -0.485380 -0.687565
4 -0.334315  1.790056  0.245414 -0.236784 -0.788226  0.483709
5 -0.943732  1.437968 -0.114556 -1.098798  0.482486 -1.527283
6 -1.213711  1.573547  0.425109  0.513945  0.731550  1.216149
7  0.709976  1.741406 -0.379932 -1.326460 -1.506532 -0.795053
Wie lautet die Syntax, um eine Kombination mehrerer Slices auszuwählen, z. B. die Auswahl von ('bar',:) und ('baz':'foo','two')? Ich weiß, dass ich so etwas tun kann:

Code: Select all

df.loc[:, [('bar', 'one'), ('baz', 'two')]]

bar       baz
one       two
0  1.018709  1.478292
1  1.388296  1.597739
2 -0.151763 -0.350483
3 -0.221250  0.077380
4 -0.334315 -0.236784
5 -0.943732 -1.098798
6 -1.213711  0.513945
7  0.709976 -1.326460
Und so etwas wie:

Code: Select all

print(df.loc[:, ('bar', slice(None))])

bar
one       two
0  1.018709  0.295048
1  1.388296  0.019284
2 -0.151763 -0.424984
3 -0.221250 -0.449578
4 -0.334315  1.790056
5 -0.943732  1.437968
6 -1.213711  1.573547
7  0.709976  1.741406
Aber so etwas wie:

Code: Select all

print(df.loc[:, [('bar', slice(None)), ('baz', 'two')]])
Löst eine TypeError-Ausnahme aus, während

Code: Select all

print(df.loc[:, ['bar', ('baz', 'two')]])
löst eine ValueError-Ausnahme aus.

Was ich also suche, ist eine einfache Syntax zum Erstellen des Folgenden mit zwei Slices wie:

Code: Select all

[('bar', slice(None)), ('baz', 'two')]
:

Code: Select all

        bar                 baz
one       two       two
0 -1.438018  1.511736  0.186499
1 -0.432313 -0.478824 -0.055930
2  0.995103 -0.181832 -0.257952
3  0.972293  2.580807  1.536281
4 -0.496261  1.038807  0.209853
5  0.788222 -1.325234 -1.328570

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post