Pandas 模块-操纵数据(1)-重命名-rename()-rename_axis()

目录

1.  重命名

1.1 .rename() 函数-修改 Dataframe 数据的行名和列名

1.1.1 .rename() 函数语法

1.1.2 .rename() 函数范例-参数 index 和 columns 

1.1.3 .rename() 函数范例-参数 mapper 和 axis

1.1.4 .rename() 函数范例-参数 copy 和 inplace

1.1.5  .rename() 函数范例-参数  level  

1.1.6  .rename() 函数范例-参数  errors

1.2 .rename_axis() 函数-设置索引或列的axis名称。

1.2.1 .rename_axis() 函数语法

1.2.2 .rename_axis() 函数范例

    在前面几小节中,已经简单的说了Pandas 模块里面的数据结构,如何创建数据,如何和外界交互读取,但是我们使用 Pandas 的主要目的还是为了清洗数据,整理数据,然后得到我们想要的结果。

1.  重命名

1.1 .rename() 函数-修改 Dataframe 数据的行名和列名

1.1.1 .rename() 函数语法

DataFrame.rename(self, mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None, errors='ignore')

参数说明:

  • mapper: 类似字典或函数,类似Dict或函数的转换,以应用于该轴的值。要么 使用 mapper 和 axis 与指定axis 的目标 进行 mapper 转换,要么使用 index 和 columns。
  • index: 类似字典或函数,指定axis (mapper, axis=0 相当于 index=mapper)的替代方法。
  • columns: 类似字典或函数,指定axis (mapper, axis=1 相当于 columns=mapper)的替代方法。
  • axis:{0 or 'index', 1 or 'columns'}, 默认为0(即' index ')
  • int 或 str,轴到目标与mapper。可以是轴名(' index ', ' columns ')或数字(0,1),
  • copy:bool, 默认 True,还要复制底层数据。
  • inplace:bool, 默认为 False,是否返回一个新的DataFrame。如果为真,则忽略copy的值。
  • level:int 或 level name, 默认 None,对于多索引,只能在指定的级别重命名标签。
  • errors:{‘ignore’, ‘raise’}, 默认 ‘ignore’。如果‘raise’,则在类似于 dict 的映射器、索引或列包含正在转换的索引中不存在的标签时引发键错误。如果 ‘ignore’,现有的键将被重命名,额外的键将被忽略。
help(pd.DataFrame.rename)
Help on function rename in module pandas.core.frame:

rename(self, mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None, errors='ignore')
    Alter axes labels.
    
    Function / dict values must be unique (1-to-1). Labels not contained in
    a dict / Series will be left as-is. Extra labels listed don't throw an
    error.
    
    See the :ref:`user guide <basics.rename>` for more.
    
    Parameters
    ----------
    mapper : dict-like or function
        Dict-like or function transformations to apply to
        that axis' values. Use either ``mapper`` and ``axis`` to
        specify the axis to target with ``mapper``, or ``index`` and
        ``columns``.
    index : dict-like or function
        Alternative to specifying axis (``mapper, axis=0``
        is equivalent to ``index=mapper``).
    columns : dict-like or function
        Alternative to specifying axis (``mapper, axis=1``
        is equivalent to ``columns=mapper``).
    axis : {0 or 'index', 1 or 'columns'}, default 0
        Axis to target with ``mapper``. Can be either the axis name
        ('index', 'columns') or number (0, 1). The default is 'index'.
    copy : bool, default True
        Also copy underlying data.
    inplace : bool, default False
        Whether to return a new DataFrame. If True then value of copy is
        ignored.
    level : int or level name, default None
        In case of a MultiIndex, only rename labels in the specified
        level.
    errors : {'ignore', 'raise'}, default 'ignore'
        If 'raise', raise a `KeyError` 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.
    
    Returns
    -------
    DataFrame or None
        DataFrame with the renamed axis labels or None if ``inplace=True``.

先准备数据

df = pd.DataFrame({"A": [0, 1, 2], "B": [3, 4, 5]})
df

1.1.2 .rename() 函数范例-参数 index 和 columns 

index 和 columns ,这两者既可以单独用,也可以组合在一起用。

如果是index 和 columns 使用 dict 形式

df.rename(index={0: "x", 1: "y", 2: "z"},# dict 替换名字
          columns={"A": "a", "B": "b"}) # dict 格式替换名字

 运行结果

 如果是index 和 columns 使用 函数形式

df.rename(index=lambda x:x+1,# lambda 函数 对 index 进行操作
          columns=lambda x:x*2) # 同上

 如果代码中的 lambda 函数换成其他内置函数或者用户定义的函数也是可以的。

例如将 index 转换成 str 类型

1.1.3 .rename() 函数范例-参数 mapper 和 axis

mapper 和 axis ,这两者需要组合在一起使用,即使 axis 没有指定,也是默认为 0 即 “index” 的。

只明确指定 mapper 参数,mapper 为 dict 

df.rename(mapper={0: "x", 1: "y", 2: "z"})# axis 为默认 0 即 index

明确指定 mapper 参数,mapper 为 dict ,明确指定 axis,采用数值方式

df.rename(mapper={"A": "a", "B": "b"},
            axis=1)# axis 为默认 1 即 index

 

 明确指定 mapper 参数,mapper 为 函数,明确指定 axis,采用字符串方式

df.rename(mapper=lambda x:x.upper(),
            axis="columns")# axis 为默认 1 即 index

 

1.1.4 .rename() 函数范例-参数 copy 和 inplace

  • copy:bool, 默认 True,还要复制底层数据。
  • inplace:bool, 默认为 False,是否返回一个新的DataFrame。如果为真,则忽略copy的值。

1.1.5  .rename() 函数范例-参数  level  

level : int or level name, default None In case of a MultiIndex, only rename labels in the specified level

1.1.6  .rename() 函数范例-参数  errors

errors : {'ignore', 'raise'}, default 'ignore'

If 'raise', raise a `KeyError` 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.

errors 这个参数非常好理解,它加强了对 error 的错误控制。

1.2 .rename_axis() 函数-设置索引或列的axis名称。

1.2.1 .rename_axis() 函数语法

DataFrame.rename_axis(self, mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False)

参数说明

Help on function rename_axis in module pandas.core.generic:

rename_axis(self, mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False)
    Set the name of the axis for the index or columns.
    
    Parameters
    ----------
    mapper : scalar, list-like, optional
        Value to set the axis name attribute.
    index, columns : scalar, list-like, dict-like or function, optional
        A scalar, list-like, dict-like or functions transformations to
        apply to that axis' values.
        Note that the ``columns`` parameter is not allowed if the
        object is a Series. This parameter only apply for DataFrame
        type objects.
    
        Use either ``mapper`` and ``axis`` to
        specify the axis to target with ``mapper``, or ``index``
        and/or ``columns``.
    
        .. versionchanged:: 0.24.0
    
    axis : {0 or 'index', 1 or 'columns'}, default 0
        The axis to rename.
    copy : bool, default True
        Also copy underlying data.
    inplace : bool, default False
        Modifies the object directly, instead of creating a new Series
        or DataFrame.
    
    Returns
    -------
    Series, DataFrame, or None
        The same type as the caller or None if ``inplace=True``.
    
    See Also
    --------
    Series.rename : Alter Series index labels or name.
    DataFrame.rename : Alter DataFrame index labels or name.
    Index.rename : Set new names on index.
    
    Notes
    -----
    ``DataFrame.rename_axis`` supports two calling conventions
    
    * ``(index=index_mapper, columns=columns_mapper, ...)``
    * ``(mapper, axis={'index', 'columns'}, ...)``
    
    The first calling convention will only modify the names of
    the index and/or the names of the Index object that is the columns.
    In this case, the parameter ``copy`` is ignored.
    
    The second calling convention will modify the names of the
    corresponding index if mapper is a list or a scalar.
    However, if mapper is dict-like or a function, it will use the
    deprecated behavior of modifying the axis *labels*.
    
    We *highly* recommend using keyword arguments to clarify your
    intent.
    
    

1.2.2 .rename_axis() 函数范例

在已经介绍 DataFrame.rename 的基础上,安装包里面的 rename_axis() 范例就足够了

Examples
    --------
    **Series**
    
    >>> s = pd.Series(["dog", "cat", "monkey"])
    >>> s
    0       dog
    1       cat
    2    monkey
    dtype: object
    >>> s.rename_axis("animal")
    animal
    0    dog
    1    cat
    2    monkey
    dtype: object
    
    **DataFrame**
    
    >>> df = pd.DataFrame({"num_legs": [4, 4, 2],
    ...                    "num_arms": [0, 0, 2]},
    ...                   ["dog", "cat", "monkey"])
    >>> df
            num_legs  num_arms
    dog            4         0
    cat            4         0
    monkey         2         2
    >>> df = df.rename_axis("animal")
    >>> df
            num_legs  num_arms
    animal
    dog            4         0
    cat            4         0
    monkey         2         2
    >>> df = df.rename_axis("limbs", axis="columns")
    >>> df
    limbs   num_legs  num_arms
    animal
    dog            4         0
    cat            4         0
    monkey         2         2
    
    **MultiIndex**
    
    >>> df.index = pd.MultiIndex.from_product([['mammal'],
    ...                                        ['dog', 'cat', 'monkey']],
    ...                                       names=['type', 'name'])
    >>> df
    limbs          num_legs  num_arms
    type   name
    mammal dog            4         0
           cat            4         0
           monkey         2         2
    
    >>> df.rename_axis(index={'type': 'class'})
    limbs          num_legs  num_arms
    class  name
    mammal dog            4         0
           cat            4         0
           monkey         2         2
    
    >>> df.rename_axis(columns=str.upper)
    LIMBS          num_legs  num_arms
    type   name
    mammal dog            4         0
           cat            4         0
           monkey         2         2

In [11]:

1

data[["id","title"]]

Out[11]:

idtitle
01Teacher
12NewMan
23Policeman
34CodingMan
45Officer
56Farmer
67Trader
78Thief
89Builder
910Singer

'''

要是大家觉得写得还行,麻烦点个赞或者收藏吧,想给博客涨涨人气,非常感谢!

'''

  • 44
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江南野栀子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值