iT邦幫忙

2025 iThome 鐵人賽

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

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

菜雞學習 pandas 的 30 日讀書分享【Day 19】loc 與 iloc

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20250819/20168290N9ObvoE3i3.png

loc 與 iloc

DataFrame 與 Series 相同,有特殊的屬性 lociloc,分別搭配標籤和整數來檢索。

因為 DataFrame 是二維的,可以使用標籤 loc 或整數 iloc,以類似 NumPy 的語法來選擇列與欄的子集合。

使用標籤來選出一列:

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

In [154]: data.loc["Colorado"]
Out[154]:
one      0
two      5
three    6
four     7
Name: Colorado, dtype: int64

選擇一列會得到一個 Series,裡面的索引是 DataFrame 的欄標籤,傳入標籤序列會選出多列並建立一個新的 DataFrame:

In [155]: data.loc[["Colorado", "New York"]]
Out[155]:
          one  two  three  four
Colorado    0    5      6     7
New York   12   13     14    15

可以在 loc 裡面同時選擇列與欄,兩者使用逗號分開:

In [156]: data.loc["Colorado", ["two", "three"]]
Out[156]:
two      5
three    6
Name: Colorado, dtype: int64

接著使用 iloc 與整數來執行類似的選擇:

In [157]: data.iloc[2]
Out[157]:
one      8
two      9
three   10
four    11
NameL Utah, dtype: int64

In [158]: data.iloc[[2, 1]]
Out[158]:
          one  two  three  four
Utah        8    9     10    11
Colorado    0    5      6     7

In [159]: data.iloc[2, [3, 0, 1]]
Out[159]:
four    11
one      8
two      9
Name: Utah, dtype: int64

In [160]: data.iloc[[1, 2], [3, 0,1]]
Out[160]:
          four  one  two
Colorado     7    0    5
Utah        11    8    9

這兩種檢索除了可以使用一個標籤或一個 Series 標籤之外,也可使用 slice:

In [161]: data.loc[:"Utah", "two"]
Out[161]:
Ohio        0
Colorado    5
Utah        9
Name: two, dtype: int64

In [162]: data.iloc[:, :3][data.three > 5]
Out[163]:
          one  two  three  four
Colorado    0    5      6     7
Utah        8    9     10    11
New York   12   13     14    15

選擇與重新排列資料的方法

  • df[colunmn]: 從 DataFrame 選出某欄或某幾欄
  • df.loc[rows]: 使用標籤從 DataFrame 選出某列或某幾列
  • df.loc[:, cols]: 使用標籤來選出某欄或某幾欄
  • df.loc[rows, cols]: 使用標籤來選出某列或某欄
  • df.iloc[rows]: 使用整數位置來選出某列或某幾列
  • df.iloc[:, cols]: 使用整數位置來選出某欄或多欄
  • df.iloc[rows, cols]: 使用整數位置來選出某列嶼某欄
  • df.at[row, col]: 使用列與欄的標籤來選出一個純量值
  • df.iat[row, col]: 使用列與欄的位置來選出一個純量值
  • reindex 方法: 使用標籤來選出某幾列或某幾欄

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


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

尚未有邦友留言

立即登入留言