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

Time:08-25

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.

CodePudding user response:

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

CodePudding user response:

In your case just do

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