gpt4 book ai didi

python - 使用 Pandas 重命名数据框列中的元素

转载 作者:太空狗 更新时间:2023-10-29 21:17:31 25 4
gpt4 key购买 nike

使用 Pandas :

df = pd.DataFrame({'n':['d','a','b','c','c','a','d','b'], 'v':[1,2,1,2,2,1,1,1]})

如何重命名 df.n 中的元素,使 a 更改为 xbycwdz,导致:

   n  v
0 z 1
1 x 2
2 y 1
3 w 2
...

最佳答案

您可以将替换值的字典传递到系列 replace 中方法:

In [11]: df['n'].replace({'a': 'x', 'b': 'y', 'c': 'w', 'd': 'z'})
Out[11]:
0 z
1 x
2 y
3 w
4 w
5 x
6 z
7 y
Name: n, dtype: object

In [12]: df['n'] = df['n'].replace({'a': 'x', 'b': 'y', 'c': 'w', 'd': 'z'})

关于python - 使用 Pandas 重命名数据框列中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18548662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com