熊猫重命名列和索引
有时候我们想要在Pandas DataFrame对象中重命名列和索引。我们可以使用pandas DataFrame rename()函数来重命名列和索引。它支持以下参数。
- mapper: dictionary or a function to apply on the columns and indexes. The ‘axis’ parameter determines the target axis – columns or indexes.
- index: must be a dictionary or function to change the index names.
- columns: must be a dictionary or function to change the column names.
- 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’.
- inplace: if True, the DataFrame is changed. Otherwise, a new DataFrame is returned and the current DataFrame remains unchanged. The default value is ‘False’.
- level: can be int or level name. It’s used in case of a MultiIndex, only rename labels in the specified level.
- 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.
关于rename()函数的一些重要要点。
-
- 以下是该原文的中文表达:
建议使用关键字参数以明确指定意图。
根据字典中的值,我们可以使用此函数重命名单个列或多个列。
让我们来看一些使用Pandas rename()函数的示例。
1. 将Pandas的列重新命名。
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)
输出:需要用中文本地化地改写以下内容,只需要一个选项:
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
上述的rename()函数调用也可以用以下方式进行编写。
df1 = df.rename(mapper={'Name': 'EmpName', 'ID': 'EmpID', 'Role': 'EmpRole'},
axis='columns') # axis=1 corresponds to columns
很明显,使用关键字参数比使用映射器和轴参数更清晰。
2. 将Pandas中的单个列进行重命名
如果您想重命名单个列,只需在columns字典参数中传递单个键值对即可。
df1 = df.rename(columns={'Name': 'EmpName'})
print(df1)
输出:只需要一个选择,用中文来解释以下内容:
EmpName ID Role
0 Pankaj 1 CEO
1 Lisa 2 Editor
2 David 3 Author
如果在列字典中存在一个非匹配的映射,则结果将相同。
df1 = df.rename(columns={'Name': 'EmpName', 'X': 'Y'}) # same result since there is no X column
3. 将Pandas索引重命名
如果你想重命名索引,请将字典作为“index”参数传递。
df2 = df.rename(index={0: '#0', 1: '#1', 2: '#2'})
print('Renamed Indexes:\n', df2)
输出:
Renamed Indexes:
Name ID Role
#0 Pankaj 1 CEO
#1 Lisa 2 Editor
#2 David 3 Author
我们还可以使用映射器和轴参数来重新命名索引。
df2 = df.rename({0: '#0', 1: '#1', 2: '#2'}, axis=0)
# axis='index' will work, first argument is assigned to 'mapper'
4. 将Pandas单个索引重新命名。
df2 = df.rename(index={1: '#1'})
print(df2)
结果:
Name ID Role
0 Pankaj 1 CEO
#1 Lisa 2 Editor
2 David 3 Author
5. 对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)
输出:
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
使用映射函数来重命名列
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)
输出:
NAME ID ROLE
0 Pankaj 1 CEO
1 Lisa 2 Editor
name id role
0 Pankaj 1 CEO
1 Lisa 2 Editor
7. 使用函数来重新命名列和索引
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)
输出:
name id role
0.00000 Pankaj 1 CEO
57.29578 Lisa 2 Editor
严格更名和抛出键错误 hé cuò)
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
结果:
Traceback (most recent call last):
File "/Users/scdev/Documents/PycharmProjects/hello-world/scdev/pandas/pandas_rename_column.py", line 58, in <module>
df1 = df.rename(columns={'Salary': 'EmpSalary'}, errors='raise')
KeyError: "['Salary'] not found in axis"
9. 参考文献
- pandas DataFrame rename() API Doc
- Python Pandas Module Tutorial