简体   繁体   English

MultiIndex Pandas不对第一级索引进行分组

[英]MultiIndex Pandas does not group first index level

I am trying to create a Pandas Dataframe with two levels of index in the rows. 我正在尝试创建一个在行中具有两个索引级别的Pandas Dataframe。

info = pd.DataFrame([['A', 1, 3],
                   ['A', 2, 4],
                   ['A', 3, 6],
                   ['B', 1, 9],
                   ['B', 2, 10],
                   ['B', 4, 6]], columns=pd.Index(['C', 'D', 'V'])    
info_new = info.set_index(['C', 'D'], drop=False)

EDIT: I want the following output: 编辑:我想要以下输出:

     V
C  D
A  1 3
   2 4
   3 6
B  1 9
   2 10
   4 6

According to every instruction I found, this should work. 根据我发现的每条指令,这应该可行。 I am still getting 我还在

     V
C  D
A  1 3
A  2 4
A  3 6
B  1 9
B  2 10
B  4 6

So apparently, the multiindex does not work here. 因此,显然,多索引在这里不起作用。

I checked each column with non-unique values with .is_unique , the answer is False. 我用.is_unique检查了每个具有非唯一值的.is_unique ,答案是False。 I checked the columns with unique values, the answer is True. 我检查了具有唯一值的列,答案为True。 I also tried to assign a dtype=str, this didn't change anything. 我也尝试分配一个dtype = str,这没有改变任何东西。

Thank you for the info_new.index.is_lexsorted() comment. 感谢您对info_new.index.is_lexsorted()评论。

I solved it by specifying dtype=str in the .csv import and then: 我通过在.csv导入中指定dtype = str来解决此问题,然后:

info_new.sortlevel(inplace=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM