简体   繁体   English

Pandas 单级多索引与普通索引

[英]Pandas single level multiindex vs plain index

One may produce single level MultiIndex in pandas like so:可以在 Pandas 中生成单级 MultiIndex,如下所示:

index = pd.MultiIndex.from_arrays([[1,2,3]])
index
print ('Number of levels = %d' % index.nlevels)
MultiIndex(levels=[[1, 2, 3]],
           codes=[[0, 1, 2]])
Number of levels = 1

And then use it as simple index, for example in order to init DataFrame:然后将其用作简单索引,例如为了初始化 DataFrame:

df = pd.DataFrame([0,0,15], index=index, columns=['d'])
df

But is there any 'special' use cases of single level multiindex instead of simple index?但是有没有单级多索引而不是简单索引的“特殊”用例? I mean the cases where simple index 'less comfortable' or even won't work.我的意思是简单索引“不太舒服”甚至不起作用的情况。

I can only think of the memory usage , if you only have one single level you should using plain index .我只能想到内存使用情况,如果您只有一个级别,则应该使用普通索引。

df.index.memory_usage()
123
df.index=[1,2,3]
df.index.memory_usage()
24

I think the behavior should be the same, but there appear to be subtle differences.我认为行为应该是相同的,但似乎存在细微的差异。

For example, the single-level MultiIndex causes problems with indexing.例如,单级 MultiIndex 会导致索引问题。 See this question: Pandas indexing error with (1) non-unique query, and (2) single-level MultiIndex看到这个问题: Pandas indexing error with (1) non-unique query, and (2) single-level MultiIndex

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

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