python如何检查字符串是否是字符串列表的元素

时间:2016-10-28 14:07:21

标签: python string list pandas dataframe

在python中,如何检查字符串是否是字符串列表的元素?

我正在使用的示例数据是:

testData=pd.DataFrame({'value':['abc','cde','fgh']})

然后为什么以下代码的结果为“False”:

testData['value'][0] in testData['value']

1 个答案:

答案 0 :(得分:5)

您可以使用向量化str.contains来测试每行中是否存在字符串:

In [262]:
testData['value'].str.contains(testData['value'][0])

Out[262]:
0     True
1    False
2    False
Name: value, dtype: bool

如果您在任何一行中是否存在,请使用any

In [264]:
testData['value'].str.contains(testData['value'][0]).any()

Out[264]:
True

好的,可以解决您的上一个问题:

In [270]:
testData['value'][0] in testData['value']

Out[270]:
False

这是因为pd.Series.__contains__已实施:

def __contains__(self, key):
    """True if the key is in the info axis"""
    return key in self._info_axis

如果我们看一下_info_axis实际上是什么:

In [269]:
testData['value']._info_axis

Out[269]:
RangeIndex(start=0, stop=3, step=1)

然后,我们可以看到'abc'中的testData['value']何时我们真正测试'abc'是否实际上在索引中,这就是它返回False <的原因/ p>

示例:

In [271]:
testData=pd.DataFrame({'value':['abc','cde','fgh']}, index=[0, 'turkey',2])
testData

Out[271]:
       value
0        abc
turkey   cde
2        fgh

In [272]:
'turkey' in testData['value']

Out[272]:
True

我们现在可以看到返回True,因为我们正在测试“火鸡”是否已经过了存在于索引

相关问题