【问题标题】:renaming pandas dataframe indeces using index and column values使用索引和列值重命名熊猫数据框索引
【发布时间】:2017-09-06 13:52:42
【问题描述】:

我有一个数据框df

df
 Name 
0   A
1   A
2   B
3   B
4   C
5   D
6   E
7   F
8   G
9   H

如何重命名数据框的 ideces,以便

df
 Name 
0_A   A
1_A   A
2_B   B
3_B   B
4_C   C
5_D   D
6_E   E
7_F   F
8_G   G
9_H   H

【问题讨论】:

    标签: python pandas dataframe indexing


    【解决方案1】:

    1.

    赋值给index拼接字符串,先强制转换为str

    df.index = df.index.astype(str) + '_' + df['Name']
    #for remove index name
    df.index.name = None
    print (df)
        Name
    0_A    A
    1_A    A
    2_B    B
    3_B    B
    4_C    C
    5_D    D
    6_E    E
    7_F    F
    8_G    G
    9_H    H
    

    2.

    set_indexrename_axis 类似的解决方案:

    df = df.set_index(df.index.astype(str) + '_' + df['Name']).rename_axis(None)
    print (df)
        Name
    0_A    A
    1_A    A
    2_B    B
    3_B    B
    4_C    C
    5_D    D
    6_E    E
    7_F    F
    8_G    G
    9_H    H
    

    3.

    str.cat 的解决方案:

    df = df.set_index(df.index.astype(str).str.cat(df['Name'], sep='_'))
    print (df)
        Name
    0_A    A
    1_A    A
    2_B    B
    3_B    B
    4_C    C
    5_D    D
    6_E    E
    7_F    F
    8_G    G
    9_H    H
    

    4.

    list comprehension解决方案:

    df.index = ['{0[0]}_{0[1]}'.format(x) for x in zip(df.index, df['Name'])]
    print (df)
        Name
    0_A    A
    1_A    A
    2_B    B
    3_B    B
    4_C    C
    5_D    D
    6_E    E
    7_F    F
    8_G    G
    9_H    H
    

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 1970-01-01
      • 2020-03-24
      • 2022-11-21
      • 2019-07-28
      • 2019-08-06
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      相关资源
      最近更新 更多