1. df[]
行為的邏輯
當 []
裡是單一字串或list of strings
- 代表你選擇一個或多個欄位(columns)
df['A'] # 取出名為'A'的column(得到Series)
df[['A', 'B']] # 取出名為'A','B'的columns(得到DataFrame)
輸出結果:
![Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool Series] 選取多個rows - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/04/20250420212553_0_6fb2c3.png)
df[[“A”,”B”]] 等效:
pd.DataFrame(dic,columns=[“A”,”B”])
![Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool Series] 選取多個rows - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/04/20250425150726_0_2b5090.png)
不要 誤以為columns 參數是
更改column name的意思,
將會取得NaN:
![Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool Series] 選取多個rows - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/04/20250425151132_0_517bb7.png)
要更改column name,
請 建立好 DataFrame 後
賦值給 DataFrame.columns:
![Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool Series] 選取多個rows - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/04/20250425151514_0_bc9b0e.png)
當 []
裡是切片(slice) 或 bool Series/array
- 代表你選擇列(rows)
df[0:2] # 取出第0、1兩行(用切片選row)
df[df['A'] > = 3] # 用布林篩選row
輸出結果:
![Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool Series] 選取多個rows - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/04/20250420213346_0_e61330.png)
2. 為什麼會這樣設計?
Pandas 設計哲學
- DataFrame 是「以欄為主」的結構
df[]
這個語法,最原始的設計,就是像dict一樣去取「欄」。df['A']
就像d['A']
df[['A','B']]
就像從dict裡挑兩個key
- 但為了方便,也允許用切片和布林遮罩直接過濾row
這是為了讓 DataFrame 有點像 Numpy array 的行為:df[0:3]
直覺上就是要「取某幾rows」df[條件]
就像 array 的「masking」
類比字典、array 的混合行為
- 像字典:「key」代表欄位
- 像陣列:「切片」或「布林陣列」代表row的篩選
3. 行為差異的合理解釋
欄位(columns)取法:
- 單一字串或list => 你是在指定欄位(key),所以是「選欄」。
列(rows)取法:
- 切片(slice) => 行的index切片(跟Numpy array一致)
- 布林Series/array => 哪些row要保留(跟Numpy array一致)
總結:
df[欄位名或list]
→ 取欄位(columns)df[切片或布林遮罩]
→ 取列(rows)
4. 更嚴謹的說法(官方文件)
The behavior of
df[]
depends on the type of the argument:
- If the argument is a string or list of strings: select columns.
- If the argument is a slice or boolean array/Series: select rows.
參考:Pandas 官方文件 – Indexing and selecting data
5. 建議
- 想選row/col都明確的話,建議用
.loc
、.iloc
,可避免混淆。
6. 記憶口訣
- df[欄位key] → 選column
- df[布林/切片] → 選row
推薦hahow線上學習python: https://igrape.net/30afN
df[0,"A"]
會觸發KeyError
![Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool Series] 選取多個rows - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/04/20250420220237_0_8ae2cb.png)
這個錯誤訊息是因為用了 df[0, "A"]
這種寫法,
但在 Pandas 裡,這不是正確的取值方式。
原因說明
df[]
只接受一個參數,這個參數是 column 名稱或 column 名稱的 list,或是 row 的 slice、boolean mask。- 你傳入了一個tuple
(0, "A")
,Pandas 會把它當成欄位名稱去查找,結果找不到這個名為(0, "A")
的欄位,所以報KeyError
。
正確的做法
如果你想「取第0列的’A’欄」:
請使用 .loc
或 .iloc
:
.loc
:用標籤(index 和 column 名稱).iloc
:用數字位置(row 和 column 的整數 index)
![Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool Series] 選取多個rows - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2025/04/20250420220509_0_47f49c.png)
延伸總結
df[0, 'A']
錯誤,因為只接受一個參數- 用
df.iloc[row_idx, col_idx]
或df.loc[row_label, col_label]
才能同時指定 row 和 column
官方文件參考
推薦hahow線上學習python: https://igrape.net/30afN
近期留言