如何自定义我的数据框索引,同时保持它们自动递增?

时间:2018-03-03 23:23:05

标签: python pandas dataframe indexing

这是我的源代码:

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

我该怎么做? 非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

请参阅pandas .set_index

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
相关问题