0

I have a data set on football players. I want to build a hierarchy by making Club and Nationality as the index. But here's what happens:

z.set_index(['Club','Nationality'])

This is the output

enter image description here

It does group some players according to their clubs and nationality but not all. What could be the problem?

Nihal
  • 5,262
  • 7
  • 23
  • 41
  • 2
    Do you need `z.set_index(['Club','Nationality']).sort_index()` ? – jezrael Jul 10 '18 at 10:42
  • Welcome to SO. Please don't includes images. Provide a [mcve]. See [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). – jpp Jul 10 '18 at 10:43
  • So I need to sort them first before grouping? – ShreyGrover Jul 10 '18 at 10:51
  • It depends what need, but grouping is only for `make the console output a bit easier on the eyes.` – jezrael Jul 10 '18 at 11:16

1 Answers1

1

You can check docs:

We’ve “sparsified” the higher levels of the indexes to make the console output a bit easier on the eyes. Note that how the index is displayed can be controlled using the multi_sparse option in pandas.set_options():

df = pd.DataFrame({'A':list('abcaac'),
                   'F':list('aaabbb'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                  }).set_index(['A','F'])

print (df)
     B  C
A F      
a a  4  7
b a  5  8
c a  4  9
a b  5  4
  b  5  2
c b  4  3

#change default value multi_sparse == True
with pd.option_context('display.multi_sparse', False):
    print(df)

     B  C
A F      
a a  4  7
b a  5  8
c a  4  9
a b  5  4
a b  5  2
c b  4  3

So if want see grouped all levels is possible sorting by sort_index:

print (df.sort_index())   
     B  C
A F      
a a  4  7
  b  5  4
  b  5  2
b a  5  8
c a  4  9
  b  4  3

#change default value multi_sparse == True
with pd.option_context('display.multi_sparse', False):
    print(df.sort_index())
     B  C
A F      
a a  4  7
a b  5  4
a b  5  2
b a  5  8
c a  4  9
c b  4  3
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252