iT邦幫忙

2025 iThome 鐵人賽

DAY 17
0
佛心分享-讓我升級的那些書

菜雞學習 pandas 的 30 日讀書分享系列 第 17

菜雞學習 pandas 的 30 日讀書分享【Day 17】從一軸移除項目

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20250816/20168290lo0V7k9QC2.png

從一軸移除項目

如果要將一軸的項目或是多個項目移除,而且已經有不含那些項目的索引陣列或串列,可以使用 reindex 方法,或使用 .loc 來檢索,這些做法可能需要使用集合邏輯做一些整理工作,所以 drop 方法可將指定值從一軸移除並回傳一個新物件:

In [113]: obj = pd.Series(np.arange(5.), index=["a", "b", "c", "d", "e"])

In [114]: obj
Out[114]:
a    0.0
b    2.0
c    3.0
d.   4.0
dtype: float64

In [115]: new_obj = obj.drop("c")

In [116]: new_obj
Out[116]:
a    0.0
b    1.0
c    3.0
d    4.0
dtype: float64

In [117]: obj.drop(["d", "c"])
Out[117]:
a    0.0
b    1.0
c    4.0
dtype: float64

使用 DataFrame 時,可以將任何軸的索引值刪除。

In [118]: data = pd.DataFrame(np.arange(16).reshape((4, 4)),
                              index=["Ohio", "Colorado", "Utah", "New York"],
                              columns=["one", "two", "three", "four"])

In [119]: data
Out[119]:
          one  two  three  four
Ohio        0    1      2     3
Colorado    4    5      6     7
Utah        8    9     10    11
New York   12   13     14    15

在呼叫 drop 時使用標籤序列會移除列標籤的值:

In [120]: data.drop(index=["Coloraod", "Ohio"])
Out[120]:
          one  two  three  four
Utah        8    9     10    11
New York   12   13     14    15

若要移除欄標籤,可以改用 columns 關鍵字:

In [121]: data.drop(index=["two"])
Out[121]:
          one  two  four
Ohio        0    2     3
Colorado    4    6     7
Utah        8   10    11
New York   12   14    15

可以藉著傳遞 axis=1 或是 axis="columns" 移除直欄的值:

In [122]: data.drop("two", axis=1)
Out[122]:
          one  two  four
Ohio        0    2     3
Colorado    4    6     7
Utah        8   10    11
New York   12   14    15

In [123]: data.drop(["two", "four"], axis="columns")
Out[123]:
          one  three
Ohio        0      2
Colorado    4      6
Utah        8     10
New York   12     14

今日的分享就到這囉,我們明天見,掰掰!!


上一篇
菜雞學習 pandas 的 30 日讀書分享【Day 16】reindex (重設索引) 下
下一篇
菜雞學習 pandas 的 30 日讀書分享【Day 18】檢索、選擇與篩選
系列文
菜雞學習 pandas 的 30 日讀書分享30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言