熊猫分发

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()函数的一些重要点。

  1. It’s recommended to use keyword arguments to clearly specify the intent.建议使用关键字参数明确指定意图。
  2. 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 pdd1 = {'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 pdd1 = {'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  AuthorSource 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  Editorname  id    role
0  Pankaj   1     CEO
1    Lisa   2  Editor

7.使用函数重命名列和索引 (7. Using functions to rename columns and indexes)

import pandas as pd
import mathdf = 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 pddf = pd.DataFrame({'NAME': ['Pankaj', 'Lisa'], 'ID': [1, 2], 'ROLE': ['CEO', 'Editor']})df1 = df.rename(columns={'Salary': 'EmpSalary'})  # unmatched mappings are ignoreddf1 = 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 TutorialPython Pandas模块教程

翻译自: https://www.journaldev.com/33457/pandas-rename-column-index

熊猫分发

熊猫分发_熊猫重命名列和索引相关推荐

  1. 熊猫分发_熊猫新手:第一部分

    熊猫分发 For those just starting out in data science, the Python programming language is a pre-requisite ...

  2. 熊猫分发_熊猫cut()函数示例

    熊猫分发 1.熊猫cut()函数 (1. Pandas cut() Function) Pandas cut() function is used to segregate array element ...

  3. 熊猫分发_熊猫下降列和行

    熊猫分发 1. Pandas drop()函数语法 (1. Pandas drop() Function Syntax) Pandas DataFrame drop() function allows ...

  4. 熊猫分发_熊猫新手:第二部分

    熊猫分发 This article is a continuation of a previous article which kick-started the journey to learning ...

  5. 熊猫分发_熊猫实用指南

    熊猫分发 什么是熊猫? (What is Pandas?) Pandas is an open-source data analysis and manipulation tool for Pytho ...

  6. 熊猫分发_与熊猫度假

    熊猫分发 While working on a project recently, I had to work with time series data spread over a year. I ...

  7. 熊猫数据集_熊猫迈向数据科学的第一步

    熊猫数据集 I started learning Data Science like everyone else by creating my first model using some machi ...

  8. pandas使用rename函数自定义重命名dataframe指定索引标签(位置)的名称(customize rename index value or label)

    pandas使用rename函数自定义重命名dataframe指定索引标签(位置)的名称(customize rename index value or label) 目录

  9. 熊猫分发_流利的熊猫

    熊猫分发 Let's uncover the practical details of Pandas' Series, DataFrame, and Panel 让我们揭露Pandas系列,DataF ...

最新文章

  1. MongoDB查询报错:class com.mongodb.MongoSecurityException: Exception authenticating MongoCredential...
  2. 2021-08-12 画蜡烛线
  3. mongodb python 大于_Python中使用MongoDB详解
  4. jboss修改服务器端口,改了默认端口的jboss不能用shutdown.sh关闭,怎样解决
  5. c语言猜四位数游戏猜10次,C语言猜数字游戏--随机生成4个不相同的数字从小到大排序,用户开始游戏,如果用户猜对数字和数字对应的位置,界面回馈A,如果数字正确位置不正确,则回馈B...
  6. 飞鸽传书也具有五华石乡特色
  7. 1-100之间 7 的倍数的个数,并打印
  8. android:layout_weight属性详解 (转)
  9. java打印出日历_java控制台打印本月的日历
  10. matlab程序设计题题库及答案,matlab程序设计例题及答案
  11. 原生 JS 实现移动端 Touch 滑动反弹
  12. 最近计算机速度测试情况,WiFi速度测试测试测试互联网速度多少兆字节
  13. php 如何使用ck播放视频,[原创]简单代码利用ckplayer播放器实现帝国CMS播放优酷在线视频...
  14. 【UOJ】#246. 【UER #7】套路
  15. 一文看懂5种ESD防护方法!
  16. 【java-调用摄像头进行截屏与保存-实例篇1-0716】
  17. linux下打开chm格式文件
  18. oracle表删除提示对象不存在,查询表结构报“ORA-04043: 对象XXX不存在”解决-Oracle...
  19. 计算机毕业设计 SSM网上购物商城系统(源码+论文)
  20. Java实现模糊搜索

热门文章

  1. java怎样实现重载一个方法
  2. 【转】Sections Headers for Android ListViews
  3. pku1063 Flip and Shift严格证明
  4. ExtJs中ComboBox使用之技巧
  5. [转载] python 需求清单_Python清单操作摘要
  6. [转载] set集合python_python基础-set集合
  7. [转载] Java8新特性-003-Java8接口中的default修饰符
  8. os.path的使用
  9. PLL与PHY的连接:通道绑定或者不绑定
  10. idea android 开发