pandas之重命名轴索引(reindex、reindex_like、rename;set_index、reset_index;set_axis)

reindex:重命名索引,如果新索引不存在原索引中,默认填充 NaN。 一般用于将已经存在的索引进行重排。没有 inplace 选项,即无法直接在 df 内部修改

>>> index = ['老王', '老张', '老何', '老魏', '老许']
>>> df = pd.DataFrame({'age': [24, 18, 36, 67, 38],
...                    'weight': [46, 57, 32, 64, 53]},
...                     index=index)
>>> df
     age  weight
老王   24      46
老张   18      57
老何   36      32
老魏   67      64
老许   38      53

# 修改行标签
>>> new_index = ['老王', '老江', '老何', '老魏', '老李']
>>> df.reindex(new_index, fill_value=0)
    age  weight
老王   24      46
老江    0       0
老何   36      32
老魏   67      64
老李    0       0

# 修改列标签
>>> df.reindex(columns=["age", "weight", "height"])
    age  weight  height
老王   24      46     NaN
老张   18      57     NaN
老何   36      32     NaN
老魏   67      64     NaN
老许   38      53     NaN

# 原数据未变
>>> df
    age  weight
老王   24      46
老张   18      57
老何   36      32
老魏   67      64
老许   38      53

reindex_like: 顾名思义,用另一个 df 的索引来更新当前 df 的索引,原索引中不存在的默认填充 None

>>> df2 = pd.DataFrame({"height": [156, 167, 178, 183, 150],
...                     "weight": [46, 57, 32, 64, 53],
...                     'age': [24, 18, 36, 67, 38]},
...                     index=index)
>>> df2
    height  weight  age
老王     156      46   24
老张     167      57   18
老何     178      32   36
老魏     183      64   67
老许     150      53   38

# 使用 df2 的索引设置 df
>>> df.reindex_like(df2)
    height  weight  age
老王     NaN      46   24
老张     NaN      57   18
老何     NaN      32   36
老魏     NaN      64   67
老许     NaN      53   38

# 原数据未变
>>> df
    age  weight
老王   24      46
老张   18      57
老何   36      32
老魏   67      64
老许   38      53

rename:修改轴标签。 可以通过字典的方式,对已经存在的索引设置一个与新索引之间的映射。有 inplace 选项,即可以直接在 df 内部修改

>>> df.rename({"老王": "王", "老许": "许"}, inplace=True)
>>> df
    age  weight
王    24      46
老张   18      57
老何   36      32
老魏   67      6438      53

rename_axis:修改行或列的标签名。

>>> df.rename_axis("feature", axis=1, inplace=True)
>>> df
feature  age  weight
王         24      46
老张        18      57
老何        36      32
老魏        67      6438      53

set_index:将某一列设置为行索引

>>> df.set_index("age", inplace=True)
>>> df
feature  weight
age
24           46
18           57
36           32
67           64
38           53

reset_index:将某一行索引放置到列中

>>> df.reset_index(inplace=True)
>>> df
feature  age  weight
0         24      46
1         18      57
2         36      32
3         67      64
4         38      53

set_axis:给指定的轴设置想要的索引。 一般用于重命名索引,不管重设的索引是否存在于原索引中

>>> df.set_axis(["A", "B"], axis=1, inplace=True)
>>> df
    A   B
0  24  46
1  18  57
2  36  32
3  67  64
4  38  53
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章