使用索引和列值重命名pandas dataframe indeces [英] renaming pandas dataframe indeces using index and column values
本文介绍了使用索引和列值重命名pandas dataframe indeces的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框 df
df
Name
0 A
1 A
2 B
3 B
4 C
5 D
6 E
7 F
8 G
9 H
如何重命名数据帧的构思,以便那个
How can I rename the ideces of the dataframe so that
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
推荐答案
1。
分配给 index
连接字符串,首先将其强制转换为 str
Assign to index
concatenated string, first cast it to 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_index
和 rename_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
这篇关于使用索引和列值重命名pandas dataframe indeces的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文