set_index not indexing in pandas

大城市里の小女人 提交于 2020-06-28 08:55:45

问题


For a simple program below, I was expecting the 2nd output to be same as first..

Why is this not happening?

It's just a order change in data1 and data2

columnList = ["PID", "Sec", "Util", "random"]

data1 = [('67123', 12, '85' , '100'),  
         ('67123', 112, '15', '100'),
         ('87878', 23, "95", '100'), 
        ]

df1 = pd.DataFrame(data1, columns=columnList)
df1 = df1.set_index(["PID", "Sec"])
print df1

         Util random

PID   Sec            

67123 12    85    100

      112   15    100

87878 23    95    100
data2 = [('67123', 12, '85' , '100'),  
         ('87878', 23, "95", '100'), 
         ('67123', 112, '15', '100'),
        ]

df2 = pd.DataFrame(data2, columns=columnList)
df2 = df2.set_index(["PID", "Sec"])
print df2
          Util random

PID   Sec            

67123 12    85    100

87878 23    95    100

67123 112   15    100

回答1:


It is default displaying of Multiindex. You can temporary change it by set parameter display.multi_sparse to False with with.

Option: display.multi_sparse

Default: True

Function: “Sparsify” MultiIndex display (don’t display repeated elements in outer levels within groups)

Available options of Pandas.

#default options
#set temporary multi_sparse to True
with pd.option_context('display.multi_sparse', True):
    print df1
    
          Util random
PID   Sec            
67123 12    85    100
      112   15    100
87878 23    95    100
    
#same as
print df1    
    
          Util random
PID   Sec            
67123 12    85    100
      112   15    100
87878 23    95    100

#set temporary multi_sparse to False    
with pd.option_context('display.multi_sparse', False):
    print df1    
          Util random
PID   Sec            
67123 12    85    100
67123 112   15    100
87878 23    95    100

If you want set it, use:

 pd.set_option('display.multi_sparse', False)

And reset:

pd.reset_option('multi_sparse')


来源:https://stackoverflow.com/questions/35961320/set-index-not-indexing-in-pandas

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