2

I have DataFrame like below:

df = pd.DataFrame({"ID" : ["1", "1", "1", "2", "3"], "value" : [10, 11, 12, 13, 14]})
df.set_index(["ID", "value"], inplace=True)

By doing so I have multiindex "ID" and "value" like below:

enter image description here

What can I do so as to have this multiindex like on the result like below:

enter image description here

I tried also other way on the data frame like below:

df = pd.DataFrame({"ID" : ["1", "1", "1", "2", "3"], "value" : [10, 11, 12, 13, 14], "a} : [1,2,3,4,5)
df.set_index(["ID", "value"], inplace=True)

And code:

#temporaly display all levels of MultiIndex
with pd.option_context('display.multi_sparse',False):
    print (df)

But result is not a "elegant" DataFrame

enter image description here

1
  • Please choose a more specific question title. Commented Jan 15, 2021 at 8:40

1 Answer 1

2

It is about diplaying, by default are hidden repeated values, link :

display.multi_sparse, True, “Sparsify” MultiIndex display (don’t display repeated elements in outer levels within groups)

df = pd.DataFrame({"ID" : ["1", "1", "1", "2", "3"], "value" : [10, 11, 12, 13, 14]})
df.set_index(["ID", "value"], inplace=True)
df['tmp'] = 1

#temporaly display all levels of MultiIndex
with pd.option_context('display.multi_sparse',False):
    print (df)
          tmp
ID value     
1  10       1
1  11       1
1  12       1
2  13       1
3  14       1

For set always display all levels (not default option):

pd.set_option('display.multi_sparse', False)
print (df)
Sign up to request clarification or add additional context in comments.

10 Comments

DO you know other way ? id does not work for me :/
@bruno845 - Can you explian more not working?
@bruno845 - Is possible see your not working code?
because you add another column, I do not want to add another column
jezrael nevertheless I do not have result as DataFrame using your code
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.