在Python Pandas中使用’in’和’not in’运算符检查DataFrame中是否存在值

在Python Pandas中使用’in’和’not in’运算符检查DataFrame中是否存在值

Pandas是一个强大的Python库,广泛用于数据处理和分析。在使用DataFrames时,经常需要检查数据集中是否存在特定值。本教程将探讨如何使用Pandas中的’in’和’not in’运算符来确定DataFrame中的值的存在或不存在。

使用”in”运算符检查值的存在

Python中的’in’运算符用于检查一个值是否存在于可迭代对象中。在Pandas的上下文中,我们可以使用’in’运算符来验证DataFrame中是否存在某个值。让我们考虑两个示例,演示了使用’in’运算符来检查DataFrame中某个值的存在。

示例1:检查DataFrame列中的值

在这个示例中,我们创建一个包含两列的DataFrame:“Name”和“Age”。我们想要检查值“Alice”是否存在于“Name”列中。通过使用’in’运算符,我们可以将该值与’Name’列中的值使用“.values”属性进行比较。

考虑下面的代码。

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”操作符为值的存在和不存在检查提供了强大的工具,便于高效地进行数据探索和分析。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程