Pandas如何使用isin在多列中查找值

Pandas如何使用isin在多列中查找值

在数据处理中,经常需要查找多列数据中包含特定值的行。为了实现这个功能,Pandas提供了一个isin()函数。本文将介绍如何使用Pandas的isin()函数在多列中查找值。

阅读更多:Pandas 教程

isin()函数

Pandas的isin()函数用于判断某个元素是否存在于一个列表或另一个Series中。若存在,则返回True;反之,返回False。下面是isin()函数的语法:

isin(values)
Python

其中,values可以是列表、数组或Series。

单列中使用isin()函数

首先,我们来看一下如何使用isin()函数在单列中查找值。假设我们有一个包含员工信息的数据集,包括员工ID、姓名和职位。我们想找到所有职位为”Manager”或”Salesperson”的员工,下面是代码:

import pandas as pd 

data = {'employee_id': [1,2,3,4,5,6],
        'name': ['John','Robert','Mark','Mary','Lisa','Lilly'],
        'position': ['Manager','Salesperson','Engineer','Salesperson','Engineer','Manager']}

df = pd.DataFrame(data)

result = df[df['position'].isin(['Manager','Salesperson'])]

print(result)
Python

输出结果如下:

   employee_id    name     position
0            1    John      Manager
1            2  Robert  Salesperson
3            4    Mary  Salesperson
5            6   Lilly      Manager
Python

在上面的代码中,我们使用isin()函数找到了职位为”Manager”或”Salesperson”的员工,并将结果保存在了变量result中。

多列中使用isin()函数

接下来,我们来看一下如何在多列中使用isin()函数。仍然假设我们有一个包含员工信息的数据集,但这次我们想找到所有职位为”Manager”或”Salesperson”且姓名包含”L”的员工。下面是代码:

import pandas as pd 

data = {'employee_id': [1,2,3,4,5,6],
        'name': ['John','Robert','Mark','Mary','Lisa','Lilly'],
        'position': ['Manager','Salesperson','Engineer','Salesperson','Engineer','Manager']}

df = pd.DataFrame(data)

result = df[df['position'].isin(['Manager','Salesperson']) & df['name'].str.contains('L')]

print(result)
Python

输出结果如下:

   employee_id   name  position
5            6  Lilly   Manager
Python

在上面的代码中,我们使用&运算符将position列和name列的筛选条件进行了组合。

总结

在本文中,我们介绍了Pandas的isin()函数,并给出了在单列和多列中使用isin()函数的示例。isin()函数可用于判断某个元素是否存在于一个列表或另一个Series中。通过使用isin()函数,我们可以快速地筛选出想要的行。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册