如何检查 Pandas 列是否具有字符串列表中的值?
在本文中,我们将了解如何检查 pandas 列是否具有Python中字符串列表中的值。
字符串列表意味着列表包含字符串作为元素,我们将检查 pandas 数据框是否具有来自字符串列表的值并在它们存在时显示它们。我们将获取列表中的字符串包含的数据框列。
创建示例数据框:
Python3
#import pandas
import pandas
# create dataframe
data = pandas.DataFrame({'name': ['sireesha', 'priyank',
'ojaswi', 'gnanesh'],
'subjects': ['java', 'networks',
'c', 'c#']})
# display
data
Python3
#import pandas
import pandas
# create dataframe
data = pandas.DataFrame({'name': ['sireesha', 'priyank',
'ojaswi', 'gnanesh'],
'subjects': ['java', 'networks',
'c', 'c#']})
# consider a list
list1 = ['sireesha', 'priyank']
# check the pandas name column
# contain the given list if strings
print(data[data['name'].isin(list1)])
# consider a list
list2 = ['java', 'c']
# check the pandas subjects column
# contain the given list if strings
print(data[data['subjects'].isin(list2)])
Python3
# import pandas
import pandas
# import numpy
import numpy
# create dataframe
data = pandas.DataFrame({'name': ['sireesha', 'priyank',
'ojaswi', 'gnanesh'],
'subjects': ['java', 'networks',
'c', 'c#']})
# consider a list
list1 = ['sireesha', 'priyank']
# check the pandas name column
# contain the given list if strings
print(data[data['name'].isin(list1)])
# consider a list
list2 = ['java', 'c']
# check the pandas subjects column
# contain the given list if strings
data[~numpy.isin(data['subjects'], list1)]
输出:
方法一:使用 isin()函数
在这种情况下,isin()函数检查包含列表中存在的字符串的 pandas 列,并在存在时返回列值,否则它不会选择数据框列。
Syntax: dataframe[dataframe[‘column_name’].isin(list_of_strings)]
where
- dataframe is the input dataframe
- list_of_strings is the list that contains strings
- column_name is the column to check the list of strings present in that column
示例:用于检查 pandas 列是否具有来自字符串列表的值的Python程序
Python3
#import pandas
import pandas
# create dataframe
data = pandas.DataFrame({'name': ['sireesha', 'priyank',
'ojaswi', 'gnanesh'],
'subjects': ['java', 'networks',
'c', 'c#']})
# consider a list
list1 = ['sireesha', 'priyank']
# check the pandas name column
# contain the given list if strings
print(data[data['name'].isin(list1)])
# consider a list
list2 = ['java', 'c']
# check the pandas subjects column
# contain the given list if strings
print(data[data['subjects'].isin(list2)])
输出:
方法 2:使用 NumPy
这里 NumPy 还使用 isin()运算符来检查 pandas 列是否具有来自字符串列表的值。
Syntax: dataframe[~numpy.isin(dataframe[‘column’], list_of_value)]
例子:
Python3
# import pandas
import pandas
# import numpy
import numpy
# create dataframe
data = pandas.DataFrame({'name': ['sireesha', 'priyank',
'ojaswi', 'gnanesh'],
'subjects': ['java', 'networks',
'c', 'c#']})
# consider a list
list1 = ['sireesha', 'priyank']
# check the pandas name column
# contain the given list if strings
print(data[data['name'].isin(list1)])
# consider a list
list2 = ['java', 'c']
# check the pandas subjects column
# contain the given list if strings
data[~numpy.isin(data['subjects'], list1)]
输出: