Showing all index values when using multiIndexing in Pandas

浪尽此生 提交于 2019-12-18 09:17:04

问题


I would like that when viewing my DataFrame I will see all values of the multiIndex, including when subsequent rows have the same index for one of the levels. Here is an example:

arrays = [['20', '50', '20', '20'],['N/A', 'N/A', '10', '30']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['Jim', 'Betty'])
pd.DataFrame([np.random.rand(1)]*4,index=index)

The output is:

                                0
Jim         Betty           
20          N/A          0.954973
50          N/A          0.954973
20          10           0.954973
            30           0.954973

I would like to have a 20 also in the south-west corner. That is, I would like my DataFrame to be:

                                0
Jim         Betty           
20          N/A          0.954973
50          N/A          0.954973
20          10           0.954973
20          30           0.954973

Is Pandas capable of doing that?


回答1:


You need set display.multi_sparse to False:

#if need temporary use option
with pd.option_context('display.multi_sparse', False):
    print (df)

                  0
Jim Betty          
20  N/A    0.201643
50  N/A    0.201643
20  10     0.201643
20  30     0.201643

If this display option is required throughout a notebook, the option can be set once and for all as follows:

# if permanent use
import pandas as pd
pd.options.display.multi_sparse = False

Documentation:

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



来源:https://stackoverflow.com/questions/38211350/showing-all-index-values-when-using-multiindexing-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!