[英]How to reset only first level of MultiIndex in pandas
I've got a DataFrame
like below:我有一个
DataFrame
如下所示:
ex = pd.DataFrame({'speed': {(1252540, 0): 0.0,
(1252540, 1): 0.0,
(1252540, 2): 0.0,
(1252541, 0): 0.0,
(1252541, 1): 0.0,
(1252541, 2): 0.0,
(1252543, 0): 0.0,
(1252543, 1): 0.0,
(1252543, 2): 0.0,
(1252544, 0): 0.0,
(1252544, 1): 0.0,
(1252544, 2): 0.0,
(1252545, 0): 0.0,
(1252545, 1): 0.0,
(1252545, 2): 0.0,
(1252546, 3): 0.0,
(1252546, 4): 0.0,
(1252546, 5): 0.0,
(1252547, 3): 0.0,
(1252547, 4): 0.0},
'unknown': {(1252540, 0): np.nan,
(1252540, 1): np.nan,
(1252540, 2): np.nan,
(1252541, 0): np.nan,
(1252541, 1): np.nan,
(1252541, 2): np.nan,
(1252543, 0): np.nan,
(1252543, 1): np.nan,
(1252543, 2): np.nan,
(1252544, 0): np.nan,
(1252544, 1): np.nan,
(1252544, 2): np.nan,
(1252545, 0): np.nan,
(1252545, 1): np.nan,
(1252545, 2): np.nan,
(1252546, 3): np.nan,
(1252546, 4): np.nan,
(1252546, 5): np.nan,
(1252547, 3): np.nan,
(1252547, 4): np.nan}})
ex.index.names = ['id', 'id2']
I'd like to set a first level of MultiIndex
to (0, 0, 0, 1, 1, 1, 2, 2, 2, ...)
so that each new value in level 0 is assigned with next integer.我想将
MultiIndex
的第一级设置为(0, 0, 0, 1, 1, 1, 2, 2, 2, ...)
,以便为 0 级中的每个新值分配下一个 integer。 Normally, I could do simple shift with something like:通常,我可以通过以下方式进行简单的转变:
idx = ex.index.get_level_values(0).to_numeric()
idx -= idx.min()
but as you can see, some values ( 1252542
) may be missing from original index, while there shouldn't be any gap in new indexing.但正如您所看到的,原始索引中可能缺少某些值(
1252542
),而新索引中不应该有任何差距。 How can I accomplish that?我怎样才能做到这一点? If I could preserve the mapping (like
1252540 -> 0, 1252541 -> 1, 1252543 -> 2...
), possibly in a form of dict, it'd great, but it's not mandatory.如果我可以保留映射(如
1252540 -> 0, 1252541 -> 1, 1252543 -> 2...
),可能是 dict 的形式,那很好,但这不是强制性的。
Let me know if this helps:让我知道这是否有帮助:
indices = ex.index.get_level_values('id').unique().sort_values()
dict = {}
for key,value in (zip(indices,range(0,len(indices)))):
dict[key] = value
ex.rename(index=dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.