[英]how to replace certain elements in the pandas dataframe index
I have a dictionary and want to use .replace to only replace the indices that are in the dictionary key withe values. 我有一本字典,并且想使用.replace来仅用值替换字典键中的索引。
dicts = {"certain index element1": "changed element1",
"certain index element2": "changed element2",
"certain index element3": "changed element3",
}
This does not work: 这不起作用:
df.replace(dicts,regex=False,inplace=True)
The df
is huge so I can not reassign all of the index from scratch. df
很大,因此我无法从头开始重新分配所有索引。 I only need to change certain elements and everything else remains the same. 我只需要更改某些元素,其他所有内容都保持不变。
If I wanted to replace certain elements within the df
(not indices) it would work but for indices it does not. 如果我想替换df
某些元素(而不是索引),它将起作用,但对于索引则无效。
Use rename(index=dicts)
使用rename(index=dicts)
example 例
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.