修改Pandas的行或列的名字(重命名)

yipeiwu_com6年前Python基础

pandas.DataFrame.rename

使用函数: DataFrame.rename(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None)

功能:更改轴标签

函数字典值必须是唯一的(1对1)。未包含在 字典/Series  中的标签将保留原样。列出的额外标签不会引发错误。

参数:

mapper, index, columns : dict-like or function, optional

dict-like or functions transformations to apply to that axis' values. Use either mapperand axis to specify the axis to target with mapper, or index and columns.

dict-like 或函数转换以应用于该轴的值。二者必选其一mapper,并使用axis指定轴与目标mapper,或index和 columns。

主要用于指定需要修改的地方:index or columns

axis : int or str, optional

Axis to target with mapper. Can be either the axis name (‘index', ‘columns') or number (0, 1). The default is ‘index'.

轴与目标mapper。可以是轴名称('index','columns')或数字(0,1)。默认为'index'。

copy : boolean, default True

Also copy underlying data

还复制基础数据

inplace : boolean, default False

Whether to return a new DataFrame. If True then value of copy is ignored.

是否返回新的DataFrame。如果为True,则忽略复制值。

level : int or level name, default None

In case of a MultiIndex, only rename labels in the specified level.

如果是MultiIndex,只重命名指定级别的标签。

返回:

renamed : DataFrame

例子

DataFrame.rename 支持两种调用约定

  • (index=index_mapper, columns=columns_mapper, ...)
  • (mapper, axis={'index', 'columns'}, ...)

我们强烈建议您使用关键字参数来阐明您的意图。

>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(index=str, columns={"A": "a", "B": "c"})
  a c
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str, columns={"A": "a", "C": "c"})
  a B
0 1 4
1 2 5
2 3 6
 
 
#使用轴样式参数
 
>>> df.rename(str.lower, axis='columns')
  a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
  A B
0 1 4
2 2 5
4 3 6

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

详解将Python程序(.py)转换为Windows可执行文件(.exe)

详解将Python程序(.py)转换为Windows可执行文件(.exe)

python开发者向普通windows用户分享程序,要给程序加图形化的界面(传送门:这可能是最好玩的python GUI入门实例! /post/165763.htm),并要将软件打包为可...

利用Python循环(包括while&for)各种打印九九乘法表的实例

利用Python循环(包括while&for)各种打印九九乘法表的实例

一.for循环打印九九乘法表 #注意:由于缩进在浏览器不好控制,请大家见谅,后续会有图片传入。 1.1 左下角   for i in range(1,10):     for j...

python self,cls,decorator的理解

1. self, cls 不是关键字 在python里面,self, cls 不是关键字,完全可以使用自己写的任意变量代替实现一样的效果 代码1 复制代码 代码如下:class MyTe...

Python用模块pytz来转换时区

前言 最近遇到了一个问题:我的server和client不是在一个时区,server时区是EDT,即美国东部时区,client,就是我自己的电脑,时区是中国标准时区,东八区。处于测试需要...

python3中rank函数的用法

网上存在这么一个例子 obj = pd.Series([7,-5,7,4,2,0,4]) obj.rank() 输出为: 0 6.5 1 1.0 2 6.5 3 4....