如何在保持数据帧索引自动递增的同时自定义数据帧索引?

2024-06-16 16:17:28 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的源代码:

Pokemon = ['Charmander', 'Bulbasaur','Squirtle','Pikachu','Eevee','Mankey']
Lvl= [10,10,10,12,10,12]

Poke_info = list(zip(Pokemon,Lvl))

Poke_df = pd.DataFrame(Poke_info, columns=['Pokemon','Lvl'])

这是我的输出:

Ouput:  Pokemon        Lvl
       ------------------
    0   Charmander    10
    1   Bulbasaur     10
    2   Squirtle      10
    3   Pikachu       12
    4   Eevee         10
    5   Mankey        12

我希望索引列名为“PokeID”,索引包含一个字符串和一个从1开始的自动递增数字,如下所示:

Ouput: PokeID    Pokemon        Lvl
       ----------------------------
        P1       Charmander    10
        P2       Bulbasaur     10
        P3       Squirtle      10
        P4       Pikachu       12
        P5       Eevee         10
        P6       Mankey        12

我怎样才能做到这一点? 非常感谢你的帮助


Tags: info源代码ziplistpokemoneeveepikachulvl
1条回答
网友
1楼 · 发布于 2024-06-16 16:17:28

见熊猫^{}

Poke_df.set_index('P' + (Poke_df.index + 1).astype(str)).rename_axis('PokeID')

返回

           Pokemon  Lvl
PokeID                 
P1      Charmander   10
P2       Bulbasaur   10
P3        Squirtle   10
P4         Pikachu   12
P5           Eevee   10
P6          Mankey   12

相关问题 更多 >