Pandas 選取欄位

在 Pandas 中,選取 DataFrame 的欄位(column)是最基本的操作之一。

範例資料

以下範例都使用這份資料:

import pandas as pd

df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie'],
    'age': [25, 30, 35],
    'city': ['Taipei', 'Tokyo', 'Seoul'],
    'salary': [50000, 60000, 70000]
})

選取單一欄位

使用中括號

# 回傳 Series
names = df['name']
print(names)

輸出:

0      Alice
1        Bob
2    Charlie
Name: name, dtype: object

使用點符號

# 回傳 Series
names = df.name
print(names)

點符號比較簡潔,但有限制:

  • 欄位名稱不能有空格或特殊字元
  • 欄位名稱不能和 DataFrame 的方法或屬性名稱衝突(如 countmean

建議統一使用中括號,避免潛在問題。

選取多個欄位

傳入欄位名稱的 list:

# 回傳 DataFrame
result = df[['name', 'age']]
print(result)

輸出:

      name  age
0    Alice   25
1      Bob   30
2  Charlie   35

使用 loc 選取欄位

loc 可以同時選取列和欄:

# 選取所有列,特定欄位
result = df.loc[:, 'name']

# 選取所有列,多個欄位
result = df.loc[:, ['name', 'age']]

# 選取欄位範圍(包含起點和終點)
result = df.loc[:, 'name':'city']

使用 iloc 選取欄位

iloc 使用數字位置:

# 選取第一欄
result = df.iloc[:, 0]

# 選取前兩欄
result = df.iloc[:, :2]

# 選取第 0、2 欄
result = df.iloc[:, [0, 2]]

排除特定欄位

使用 drop() 排除不要的欄位:

# 排除單一欄位
result = df.drop('salary', axis=1)

# 排除多個欄位
result = df.drop(['salary', 'city'], axis=1)

或使用 list comprehension:

# 選取除了 salary 以外的所有欄位
cols = [c for c in df.columns if c != 'salary']
result = df[cols]

用條件選取欄位

選取特定型別的欄位

# 只選取數值型欄位
numeric_cols = df.select_dtypes(include=['number'])

# 只選取文字型欄位
text_cols = df.select_dtypes(include=['object'])

# 排除特定型別
non_numeric = df.select_dtypes(exclude=['number'])

用欄位名稱篩選

# 選取名稱包含 'a' 的欄位
cols = [c for c in df.columns if 'a' in c]
result = df[cols]

# 選取名稱以 'a' 開頭的欄位
cols = [c for c in df.columns if c.startswith('a')]
result = df[cols]

使用 filter() 方法:

# 欄位名稱包含 'a'
result = df.filter(like='a')

# 用正規表達式篩選
result = df.filter(regex='^a')  # 以 a 開頭

重新排列欄位順序

# 指定欄位順序
df = df[['city', 'name', 'age', 'salary']]

# 把某欄移到最前面
cols = ['city'] + [c for c in df.columns if c != 'city']
df = df[cols]

取得欄位名稱清單

# 取得所有欄位名稱
print(df.columns)
# Index(['name', 'age', 'city', 'salary'], dtype='object')

# 轉成 list
print(df.columns.tolist())
# ['name', 'age', 'city', 'salary']