使用 Python Pandas 中的"in"和"not in"运算符检查 DataFrame 中是否存在值
Pandas 是一个功能强大的 Python 库,广泛用于数据操作和分析。使用 DataFrame 时,通常需要检查数据集中是否存在特定值。在本教程中,我们将探讨如何使用 Pandas 中的"in"和"not in"运算符来确定 DataFrame 中是否存在值。
使用"in"运算符检查值
Python 中的"in"运算符用于检查可迭代对象中是否存在值。在 Pandas 上下文中,我们可以使用"in"运算符来验证 DataFrame 中是否存在值。让我们考虑两个示例,它们演示了如何使用"in"运算符来检查数据框中值的存在性。
示例 1:检查数据框列中的值
在此示例中,我们创建一个包含两列的数据框:"Name"和"Age"。我们想要检查"Name"列中是否存在值"Alice"。通过使用"in"运算符,我们使用".values"属性将该值与"Name"列中存在的值进行比较。
请考虑下面显示的代码。
import pandas as pd
# 创建 DataFrame
df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob', 'Emily'],'Age': [25, 30, 28, 35]})
# 检查"Name"列中是否存在值
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 存在于 DataFrame 中。
示例 2:检查 DataFrame 中的值
在此示例中,我们要检查值"28"是否存在于 DataFrame 中的任何地方。我们利用"in"运算符使用".values"属性将该值与 DataFrame 中的所有值进行比较。
考虑下面显示的代码 -
import pandas as pd
# 创建 DataFrame
df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob', 'Emily'],'Age': [25, 30, 28, 35]})
# 检查 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"。我们旨在检查"Name"列中是否存在值"Michael"。
通过使用"not in"运算符,我们使用".values"属性将该值与"Name"列中的值进行比较。
请考虑下面显示的代码。
import pandas as pd
# 创建 DataFrame
df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob', 'Emily'],'Age': [25, 30, 28, 35]})
# 检查"Name"列中是否存在值
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"运算符为值存在和不存在检查提供了强大的工具,有助于实现高效的数据探索和分析。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

