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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18548662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:01:03  来源:igfitidea点击:

rename elements in a column of a data frame using pandas

pythonpandasdataframerename

提问by HappyPy

Using pandas:

使用熊猫:

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

How can I rename the elements in df.n, such that achanges to x, bto y, cto wand dto z, resulting in:

如何重命名的元素df.n,这样a的变化xbycw,并dz,导致:

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

采纳答案by Andy Hayden

You can pass a dictionary of replacement values into the Series replacemethod:

您可以将替换值字典传递给系列替换方法:

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'})