简体   繁体   English

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

[英]rename elements in a column of a data frame using pandas

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 a changes to x , b to y , c to w and d to z , resulting in:如何重命名df.n中的元素,以便将a更改为x ,将b更改为y ,将c更改为w并将d更改为z ,从而导致:

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

You can pass a dictionary of replacement values into the Series replace method:您可以将替换值字典传递给 Series 替换方法:

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

You can also use the below one:您也可以使用以下一种:

df['n'].replace(['a', 'b', 'c', 'd'], ['x', 'y', 'w', 'z'])

Replace all the a with x, b with y, c with w, and d with z.将所有 a 替换为 x,将 b 替换为 y,将 c 替换为 w,将 d 替换为 z。 Note: if you pass two lists they both much be the same length注意:如果您传递两个列表,它们的长度几乎相同

Slightly Modified from above:从上面稍微修改:

movies['price'].replace({"$":"low","$$":"moderate","$$$":"high","$$$$":"very high"},inplace=True)电影['price'].replace({"$":"low","$$":"中等","$$$":"high","$$$$":"非常高"},就地=真)

"Use inplace =True " otherwise dataframe won't be updated. “使用 inplace =True ”否则数据框将不会被更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM