DataFrame.rename

DataFrame.rename(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None, errors=’ignore’)
修改轴标签名。

Parameters

mapper 应用于该轴的值的字典或函数的转换
index 作用于行标签
columns 作用于列标签
axis 0或index:作用于行;1或columns:作用于列
copy 是否复制
inplace False:返回一个副本;True:就地执行操作并返回None
level 指定MultiIndex的索引级别
errors raise:引发异常;ignore:忽略异常

Example

  1. import pandas as pd
  2. df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
  3. 'age':[18, 39, 22, 45],
  4. 'price': [1.0, 2.0, 3.0, 4.0],
  5. 'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
  6. df.rename(columns={'site': 'new_site', 'age': 'new_age'})
  7. -------------------------------------------------------------------
  8. new_site new_age price color
  9. first google 18 1.0 red
  10. second baidu 39 2.0 black
  11. third wiki 22 3.0 None
  12. forth pandas 45 4.0 red

Example

  1. import pandas as pd
  2. df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
  3. 'age':[18, 39, 22, 45],
  4. 'price': [1.0, 2.0, 3.0, 4.0],
  5. 'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
  6. df.rename(index={'first': 'a', 'second': 'b'})
  7. ----------------------------------------------------------------------
  8. site age price color
  9. a google 18 1.0 red
  10. b baidu 39 2.0 black
  11. third wiki 22 3.0 None
  12. forth pandas 45 4.0 red

Example

  1. import pandas as pd
  2. df = pd.DataFrame({'Y21 May.':['google', 'baidu', 'wiki', 'pandas'],
  3. 'Y21 Jun.':[18, 39, 22, 45],
  4. 'Y21 Jul.': [1.0, 2.0, 3.0, 4.0],
  5. 'Y21 Aug.': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
  6. df.rename(datetime.datetime.strptime(x, "Y%y %b."), axis=1)
  7. -----------------------------------------------------------------
  8. 2021-05-01 2021-06-01 2021-07-01 2021-08-01
  9. first google 18 1.0 red
  10. second baidu 39 2.0 black
  11. third wiki 22 3.0 None
  12. forth pandas 45 4.0 red