set_index 不在 pandas 中建立索引

2024-04-17

对于下面的简单程序,我期望第二个输出与第一个输出相同。

为什么这没有发生?

这只是订单的改变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

默认显示的是Multiindex。您可以通过设置参数临时更改它display.multi_sparse to False with with.

Option:显示.multi_sparse

Default: True

Function:“Sparsify”多索引显示(不显示组内外部级别的重复元素)

可用选项 http://pandas.pydata.org/pandas-docs/stable/options.html#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

如果你想set it http://pandas.pydata.org/pandas-docs/stable/options.html#setting-startup-options-in-python-ipython-environment, use:

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

并重置:

pd.reset_option('multi_sparse')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

set_index 不在 pandas 中建立索引 的相关文章