简体   繁体   中英

How do you get a cross section of data from a Pandas dataframe with a key for a MultiIndex?

I have a dataframe like this

A, B, C
d, 1, 2
d, 3, 4
e, 5, 6
e, 7, 8

I am trying to get

B, C
1, 2
3, 4

and

B, C
5, 6
7, 8

By iterating through d, e, etc.

I can get the keys just fine looping though df.index.levels[0]

I can not figure out how to get a cross section of the data though. I have tried this

df.xs(key=df.index.levels[0][0], level=df.index.levels[0])

but I get this error

{ValueError}The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have no clue what a is, but this does not work

df.xs(key=df.index.levels[0][0], level=df.index.levels[0]).all()

Same error message.

The docs make it sound like xs should work like that, so I am at a loss.

You can use df.loc to get your desired output.

for i in df['A'].unique():
    print(df.loc[df['A'] == i][['B','C']])

   B  C
0  1  2
1  3  4

   B  C
2  5  6
3  7  8

In your case just do

for x, y in df.groupby('A'):
    print(y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM