如何替换pandas数据帧索引

时间:2017-01-24 00:27:33

标签: python pandas dictionary indexing replace

我有一个字典,并希望使用.replace只用值替换字典键中的索引。

dicts = {"certain index element1": "changed element1",
             "certain index element2": "changed element2",
             "certain index element3": "changed element3",
             } 

这不起作用:

df.replace(dicts,regex=False,inplace=True)

df非常庞大,因此无法从头开始重新分配所有索引。我只需要改变某些元素,其他一切都保持不变。

如果我想替换df(不是索引)中的某些元素,它会起作用,但对于索引却不起作用。

1 个答案:

答案 0 :(得分:2)

使用rename(index=dicts)

示例

df = pd.DataFrame(
    np.random.choice(list('abcd'), (10, 10)),
    list('ABCDEFGHIJ')
)
dc = {'A': '_A_', 'B': '_B_'}

df.rename(index=dc, inplace=True)

print(df)

     0  1  2  3  4  5  6  7  8  9
_A_  a  a  a  a  b  a  d  c  c  b
_B_  b  c  c  a  a  a  b  b  a  b
C    b  b  d  b  d  c  c  a  a  b
D    d  d  d  d  c  b  b  a  a  d
E    d  c  c  c  a  d  a  d  d  a
F    d  c  d  c  d  d  d  d  b  d
G    b  c  d  c  c  b  c  a  a  b
H    c  c  c  b  b  a  a  b  c  a
I    c  a  a  b  a  d  c  c  a  a
J    a  a  a  c  a  b  d  c  c  c