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
import pandas as pddf = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],'age':[18, 39, 22, 45],'price': [1.0, 2.0, 3.0, 4.0],'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])df.rename(columns={'site': 'new_site', 'age': 'new_age'})-------------------------------------------------------------------new_site new_age price colorfirst google 18 1.0 redsecond baidu 39 2.0 blackthird wiki 22 3.0 Noneforth pandas 45 4.0 red
Example
import pandas as pddf = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],'age':[18, 39, 22, 45],'price': [1.0, 2.0, 3.0, 4.0],'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])df.rename(index={'first': 'a', 'second': 'b'})----------------------------------------------------------------------site age price colora google 18 1.0 redb baidu 39 2.0 blackthird wiki 22 3.0 Noneforth pandas 45 4.0 red
Example
import pandas as pddf = pd.DataFrame({'Y21 May.':['google', 'baidu', 'wiki', 'pandas'],'Y21 Jun.':[18, 39, 22, 45],'Y21 Jul.': [1.0, 2.0, 3.0, 4.0],'Y21 Aug.': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])df.rename(datetime.datetime.strptime(x, "Y%y %b."), axis=1)-----------------------------------------------------------------2021-05-01 2021-06-01 2021-07-01 2021-08-01first google 18 1.0 redsecond baidu 39 2.0 blackthird wiki 22 3.0 Noneforth pandas 45 4.0 red
