使用 Python Pandas 中的 'in' 和 'not in' 運算子檢查 DataFrame 中是否存在值
Pandas 是一個功能強大的 Python 庫,廣泛用於資料處理和分析。在處理 DataFrame 時,經常需要檢查特定值是否在資料集中存在。在本教程中,我們將探討如何在 Pandas 中使用 'in' 和 'not in' 運算子來確定 DataFrame 中值的存在或不存在。
使用 "in" 運算子檢查值
Python 中的 'in' 運算子用於檢查值是否在可迭代物件中存在。在 Pandas 的上下文中,我們可以使用 'in' 運算子來驗證值是否在 DataFrame 中存在。讓我們考慮兩個示例,演示如何使用 'in' 運算子檢查資料框中值的存在。
示例 1:檢查 DataFrame 列中的值
在本例中,我們建立了一個包含兩列的 DataFrame:'Name' 和 'Age'。我們想要檢查值 'Alice' 是否存在於 'Name' 列中。透過使用 'in' 運算子,我們使用 ".values" 屬性將該值與 'Name' 列中存在的值進行比較。
請考慮以下程式碼。
import pandas as pd # Create a DataFrame df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob', 'Emily'],'Age': [25, 30, 28, 35]}) # Check if a value exists in the 'Name' column value = 'Alice' if value in df['Name'].values: print(f"{value} exists in the DataFrame.") else: print(f"{value} does not exist in the DataFrame.")
輸出
如果找到該值,則顯示相應的郵件;否則,將列印不同的郵件。
執行此程式碼時,將產生以下輸出:
Alice exists in the DataFrame.
示例 2:檢查 DataFrame 中的值
在本例中,我們想要檢查值 '28' 是否存在於 DataFrame 中的任何位置。我們使用 "in" 運算子使用 ".values" 屬性將該值與 DataFrame 中的所有值進行比較。
請考慮以下程式碼:
import pandas as pd # Create a DataFrame df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob', 'Emily'],'Age': [25, 30, 28, 35]}) # Check if a value exists in the DataFrame value = 28 if value in df.values: print(f"{value} exists in the DataFrame.") else: print(f"{value} does not exist in the DataFrame.")
輸出
如果該值存在,則顯示相應的郵件;否則,將列印不同的郵件。
執行此程式碼時,將產生以下輸出:
28 exists in the DataFrame.
使用 "not in" 運算子檢查值
在本例中,我們建立了一個包含兩列的 DataFrame:"Name" 和 "Age"。我們的目標是檢查值 "Michael" 是否不存在於 'Name' 列中。
透過使用 "not in" 運算子,我們使用 ".values" 屬性將該值與 "Name" 列中的值進行比較。
請考慮以下程式碼。
import pandas as pd # Create a DataFrame df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob', 'Emily'],'Age': [25, 30, 28, 35]}) # Check if a value does not exist in the 'Name' column value = 'Michael' if value not in df['Name'].values: print(f"{value} does not exist in the DataFrame.") else: print(f"{value} exists in the DataFrame.")
輸出
如果未找到該值,則顯示相應的郵件;否則,將列印不同的郵件。
執行此程式碼時,將產生以下輸出:
Michael does not exist in the DataFrame.
結論
在本教程中,我們探討了如何在 Pandas 中使用 "in" 和 "not in" 運算子來檢查 DataFrame 中值的存在或不存在。透過利用這些運算子,我們可以有效地確定特定列或整個 DataFrame 中值的存在或不存在。
透過提供的程式碼示例,我們演示瞭如何使用 'in' 運算子來檢查值是否存在於 DataFrame 列中或整個 DataFrame 中。此外,我們展示瞭如何使用 'not in' 運算子來檢查值的不存在。
透過使用這些運算子,分析師和資料科學家可以有效地驗證資料的存在或不存在,使他們能夠根據 DataFrame 結構中可用的資訊做出明智的決策。
總之,Pandas 中的 "in" 和 "not in" 運算子為值存在和不存在檢查提供了強大的工具,有助於高效地進行資料探索和分析。