Python Pandas - 布林掩碼



Pandas 中的布林掩碼是一種基於特定條件過濾資料的有用技術。它的工作原理是建立一個布林掩碼,並將其應用於 DataFrame 或 Series 以選擇滿足給定條件的資料。布林掩碼是一個 DataFrame 或 Series,其中每個元素都用 True 或 False 表示。當您將此布林掩碼應用於您的資料時,它將只選擇滿足定義條件的行或列。

在本教程中,我們將學習如何在 Pandas 中應用布林掩碼並根據索引和列值過濾資料。

使用布林掩碼選擇資料

DataFrame 中的資料選擇或過濾是透過建立定義行選擇條件的布林掩碼來完成的。

示例

以下示例演示如何使用布林掩碼過濾資料。

import pandas as pd

# Create a sample DataFrame
df= pd.DataFrame({'Col1': [1, 3, 5, 7, 9],
'Col2': ['A', 'B', 'A', 'C', 'A']})

# Dispaly the Input DataFrame
print('Original DataFrame:\n', df)

# Create a boolean mask
mask = (df['Col2'] == 'A') & (df['Col1'] > 4)

# Apply the mask to the DataFrame
filtered_data = df[mask]

print('Filtered Data:\n',filtered_data)

以下是上述程式碼的輸出:

Original DataFrame:
Col1Col2
01A
13B
25A
37C
49A
Filtered Data:
Col1Col2
25A
49A

基於索引值掩碼資料

可以透過為索引建立掩碼來根據 DataFrame 的索引值過濾資料,以便您可以根據其位置或標籤選擇行。

示例

此示例使用 **df.isin()** 方法根據索引標籤建立布林掩碼。

import pandas as pd

# Create a DataFrame with a custom index
df = pd.DataFrame({'A1': [10, 20, 30, 40, 50], 'A2':[9, 3, 5, 3, 2]
}, index=['a', 'b', 'c', 'd', 'e'])

# Dispaly the Input DataFrame
print('Original DataFrame:\n', df)

# Define a mask based on the index
mask = df.index.isin(['b', 'd'])

# Apply the mask
filtered_data = df[mask]

print('Filtered Data:\n',filtered_data)

以下是上述程式碼的輸出:

Original DataFrame:
A1A2
a109
b203
c305
d403
e502
Filtered Data:
A1A2
b203
d403

基於列值掩碼資料

除了根據索引值進行過濾外,您還可以使用布林掩碼根據特定的列值過濾資料。**df.isin()** 方法用於檢查列中的值是否與值的列表匹配。

示例

以下示例演示如何建立和應用布林掩碼以根據 DataFrame 列值選擇資料。

import pandas as pd

# Create a DataFrame
df= pd.DataFrame({'A': [1, 2, 3],'B': ['a', 'b', 'f']})

# Dispaly the Input DataFrame
print('Original DataFrame:\n', df)

# Define a mask for specific values in column 'A' and 'B'
mask = df['A'].isin([1, 3]) | df['B'].isin(['a'])

# Apply the mask using the boolean indexing
filtered_data = df[mask]

print('Filtered Data:\n', filtered_data)

以下是上述程式碼的輸出:

Original DataFrame:
AB
01a
12b
23f
Filtered Data:
AB
01a
23f
廣告