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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章