子字符串列表与字符串列表的布尔比较

学习者

我有研究,但未找到以下问题的答案。

如何对字符串列表中的子字符串列表进行布尔比较?

下面是代码:

string = {'strings_1': ['AEAB', 'AC', 'AI'], 
             'strings_2':['BB', 'BA', 'AG'], 
             'strings_3': ['AABD', 'DD', 'PP'], 
             'strings_4': ['AV', 'AB', 'BV']}

df_string = pd.DataFrame(data = string)

substring_list = ['AA', 'AE']

for row in df_string.itertuples(index = False):
    combine_row_str = [row[0], row[1], row[2]]

    #below is the main operation
    print(all(substring in row_str for substring in substring_list for row_str in combine_row_str))

我得到的输出是:

False
False
False

我想要的输出是:

True
False
False
用户名

由于您使用的是熊猫,因此您可以使用正则表达式调用逐行应用和str.contains来查找字符串是否匹配。第一步是查找是否有任何值与substring_list中的字符串匹配:

df_string.apply(lambda x: x.str.contains('|'.join(substring_list)), axis=1)

这将返回:

   strings_1  strings_2  strings_3  strings_4
0       True      False       True      False
1      False      False      False      False
2      False      False      False      False

现在,还不清楚的是,如果两个子字符串都出现在一行中,或者只出现在两个子字符串中,那么您是否要返回true。如果只有它们之一,则可以在contains()方法之后简单地添加any():

df_string.apply(lambda x: x.str.contains('|'.join(substring_list)).any(), axis=1)

这将返回:

0     True
1    False
2    False
dtype: bool

对于第二种情况,jpp提供了一种将行元素缩成一个字符串的单行解决方案,但是请注意,当您连续有两个元素(例如“ BBA”和“ ABB”)并尝试匹配“ AA”。字符串“ BBAABB”仍然会匹配“ AA”,这是错误的。我想提出一个带有apply和额外功能的解决方案,以使代码更具可读性:

def areAllPresent(vals, patterns):
  result = []
  for pat in patterns:
    result.append(any([pat in val for val in vals]))
  return all(result)

df_string.apply(lambda x: areAllPresent(x.values, substring_list), axis=1)

由于您的示例数据框,它仍将返回相同的结果,但适用于需要将两者都匹配的情况:

0     True
1    False
2    False
dtype: bool

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章