目录
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 的主要目的还是为了清洗数据,整理数据,然后得到我们想要的结果。
DataFrame.rename(self, mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None, errors='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` 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
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 类型
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
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.
errors 这个参数非常好理解,它加强了对 error 的错误控制。
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.
在已经介绍 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 2In [11]:
1
data[["id","title"]]Out[11]:
id title 0 1 Teacher 1 2 NewMan 2 3 Policeman 3 4 CodingMan 4 5 Officer 5 6 Farmer 6 7 Trader 7 8 Thief 8 9 Builder 9 10 Singer
'''
要是大家觉得写得还行,麻烦点个赞或者收藏吧,想给博客涨涨人气,非常感谢!
'''