gpt4 book ai didi

python - 如何仅重置 Pandas 中的第一级MultiIndex

转载 作者:行者123 更新时间:2023-12-05 06:22:53 31 4
gpt4 key购买 nike

我有一个如下所示的 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']

我想将 MultiIndex 的第一级设置为 (0, 0, 0, 1, 1, 1, 2, 2, 2, ...) 以便为 0 级中的每个新值分配下一个整数。通常,我可以用类似的东西做简单的转变:

idx = ex.index.get_level_values(0).to_numeric()
idx -= idx.min()

但如您所见,原始索引中可能缺少某些值 (1252542),而新索引中不应有任何间隙。我怎样才能做到这一点?如果我可以保留映射(如 1252540 -> 0, 1252541 -> 1, 1252543 -> 2...),可能以字典的形式,那很好,但这不是强制性的.

最佳答案

如果这有帮助,请告诉我:

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)

关于python - 如何仅重置 Pandas 中的第一级MultiIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58899386/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com