熊猫分发
Sometimes we want to rename columns and indexes in the Pandas DataFrame object. We can use pandas DataFrame rename() function to rename columns and indexes. It supports the following parameters.
有时我们想重命名Pandas DataFrame对象中的列和索引。 我们可以使用pandas DataFramename()函数来重命名列和索引。 它支持以下参数。
- mapper: dictionary or a function to apply on the columns and indexes. The ‘axis’ parameter determines the target axis – columns or indexes. mapper :字典或要应用于列和索引的函数。 'axis'参数确定目标轴-列或索引。
- index: must be a dictionary or function to change the index names. index :必须是字典或函数才能更改索引名称。
- columns: must be a dictionary or function to change the column names. columns :必须是字典或函数才能更改列名。
- axis: can be int or string. It’s used with ‘mapper’ parameter to define the target axis. The allowed values are (‘index’, ‘columns’) or number (0, 1). The default value is ‘index’. axis :可以是int或字符串。 它与“ mapper”参数一起使用以定义目标轴。 允许的值为(“索引”,“列”)或数字(0、1)。 默认值为“索引”。
- inplace: if True, the DataFrame is changed. Otherwise, a new DataFrame is returned and the current DataFrame remains unchanged. The default value is ‘False’. 就地 :如果为true,数据帧被改变。 否则,将返回一个新的DataFrame,并且当前DataFrame保持不变。 默认值为“ False”。
- level: can be int or level name. It’s used in case of a MultiIndex, only rename labels in the specified level. level :可以是int或级别名称。 用于MultiIndex时,仅重命名指定级别的标签。
- errors: possible values are (‘ignore’, ‘raise’), default is ‘ignore’. If specified as ‘raise’ then KeyError is raised when a dict-like ‘mapper’, ‘index’, or ‘columns’ contains labels that are not present in the Index being transformed. If ‘ignore’, existing keys will be renamed and extra keys will be ignored. 错误 :可能的值为('ignore','raise'),默认值为'ignore'。 如果指定为“ raise”,则当类似dict的“ mapper”,“ index”或“ columns”包含要转换的Index中不存在的标签时,将引发KeyError。 如果为“ ignore”,则现有键将被重命名,多余的键将被忽略。
Some important points about rename() function.
有关rename()函数的一些重要点。
- It’s recommended to use keyword arguments to clearly specify the intent. 建议使用关键字参数明确指定意图。
- We can rename single column or multiple columns with this function, depending on the values in the dictionary. 我们可以使用此函数重命名单列或多列,具体取决于字典中的值。
Let’s look into some examples of using Pandas rename() function.
让我们看一些使用Pandas named()函数的示例。
1.熊猫重命名列 (1. Pandas Rename Columns)
import pandas as pd
d1 = {'Name': ['Pankaj', 'Lisa', 'David'], 'ID': [1, 2, 3], 'Role': ['CEO', 'Editor', 'Author']}
df = pd.DataFrame(d1)
print('Source DataFrame:\n', df)
# rename columns
df1 = df.rename(columns={'Name': 'EmpName', 'ID': 'EmpID', 'Role': 'EmpRole'})
print('Result DataFrame:\n', df1)
Output:
输出:
Source DataFrame:
Name ID Role
0 Pankaj 1 CEO
1 Lisa 2 Editor
2 David 3 Author
Result DataFrame:
EmpName EmpID EmpRole
0 Pankaj 1 CEO
1 Lisa 2 Editor
2 David 3 Author
The above rename() function call can also be written in the following way.
上面的rename()函数调用也可以按以下方式编写。
df1 = df.rename(mapper={'Name': 'EmpName', 'ID': 'EmpID', 'Role': 'EmpRole'},
axis='columns') # axis=1 corresponds to columns
It’s clear that using the keyword arguments is clearer than using the mapper and axis arguments.
显然,使用关键字参数比使用映射器和轴参数更清晰。
2.熊猫重命名单列 (2. Pandas Rename Single Column)
If you want to rename a single column, just pass the single key-value pair in the columns dict parameter.
如果要重命名单个列,只需在column dict参数中传递单个键值对即可。
df1 = df.rename(columns={'Name': 'EmpName'})
print(df1)
Output:
输出:
EmpName ID Role
0 Pankaj 1 CEO
1 Lisa 2 Editor
2 David 3 Author
The result will be the same if there is a non-matching mapping in the columns dictionary.
如果在列字典中存在不匹配的映射,则结果将相同。
df1 = df.rename(columns={'Name': 'EmpName', 'X': 'Y'}) # same result since there is no X column
3.熊猫重命名索引 (3. Pandas Rename Indexes)
If you want to rename indexes, pass the dict for ‘index’ parameter.
如果要重命名索引,请为“ index”参数传递dict。
df2 = df.rename(index={0: '#0', 1: '#1', 2: '#2'})
print('Renamed Indexes:\n', df2)
Output:
输出:
Renamed Indexes:
Name ID Role
#0 Pankaj 1 CEO
#1 Lisa 2 Editor
#2 David 3 Author
We can also rename indexes using mapper and axis arguments.
我们还可以使用mapper和axis参数重命名索引。
df2 = df.rename({0: '#0', 1: '#1', 2: '#2'}, axis=0)
# axis='index' will work, first argument is assigned to 'mapper'
4.熊猫重命名单一索引 (4. Pandas Rename Single Index)
df2 = df.rename(index={1: '#1'})
print(df2)
Output:
输出:
Name ID Role
0 Pankaj 1 CEO
#1 Lisa 2 Editor
2 David 3 Author
5.就地更改DataFrame (5. Changing the DataFrame inplace)
If you want to change the source DataFrame itself, pass the inplace argument as True.
如果要更改源DataFrame本身,则将inplace参数传递为True。
import pandas as pd
d1 = {'Name': ['Pankaj', 'Lisa', 'David'], 'ID': [1, 2, 3], 'Role': ['CEO', 'Editor', 'Author']}
df = pd.DataFrame(d1)
print('Source DataFrame:\n', df)
df.rename(index={0: '#0', 1: '#1', 2: '#2'}, columns={'Name': 'EmpName', 'ID': 'EmpID', 'Role': 'EmpRole'}, inplace=True)
print('Source DataFrame:\n', df)
Output:
输出:
Source DataFrame:
Name ID Role
0 Pankaj 1 CEO
1 Lisa 2 Editor
2 David 3 Author
Source DataFrame:
EmpName EmpID EmpRole
#0 Pankaj 1 CEO
#1 Lisa 2 Editor
#2 David 3 Author
6.使用映射器功能重命名列 (6. Using mapper function to rename columns)
df = pd.DataFrame({'NAME': ['Pankaj', 'Lisa'], 'ID': [1, 2], 'ROLE': ['CEO', 'Editor']})
print(df)
df.rename(mapper=str.lower, axis=1, inplace=True)
print(df)
Output:
输出:
NAME ID ROLE
0 Pankaj 1 CEO
1 Lisa 2 Editor
name id role
0 Pankaj 1 CEO
1 Lisa 2 Editor
7.使用函数重命名列和索引 (7. Using functions to rename columns and indexes)
import pandas as pd
import math
df = pd.DataFrame({'NAME': ['Pankaj', 'Lisa'], 'ID': [1, 2], 'ROLE': ['CEO', 'Editor']})
df.rename(columns=str.lower, index=math.degrees, inplace=True)
print(df)
Output:
输出:
name id role
0.00000 Pankaj 1 CEO
57.29578 Lisa 2 Editor
8.严格重命名并引发KeyError (8. Strict Rename and Raising KeyError)
import pandas as pd
df = pd.DataFrame({'NAME': ['Pankaj', 'Lisa'], 'ID': [1, 2], 'ROLE': ['CEO', 'Editor']})
df1 = df.rename(columns={'Salary': 'EmpSalary'}) # unmatched mappings are ignored
df1 = df.rename(columns={'Salary': 'EmpSalary'}, errors='raise') # unmatched mappings raising KeyError
Output:
输出:
Traceback (most recent call last):
File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/pandas/pandas_rename_column.py", line 58, in <module>
df1 = df.rename(columns={'Salary': 'EmpSalary'}, errors='raise')
KeyError: "['Salary'] not found in axis"
9.参考 (9. References)
- pandas DataFrame rename() API Doc 熊猫DataFrame named()API文档
- Python Pandas Module Tutorial Python Pandas模块教程
翻译自: https://www.journaldev.com/33457/pandas-rename-column-index
熊猫分发