【问题标题】:Python Pandas: check if Series contains a string from listPython Pandas:检查Series是否包含列表中的字符串
【发布时间】:2021-03-22 09:40:54
【问题描述】:

我正在尝试确定列 Blaze[Info] 是否在文本中包含来自列表的字符串(并使用该信息创建一个新的布尔列)。

DataFrame 看起来像:

       Word          Info
0      Aam           Aam, n. Etym: [D. aam, fr. LL. ama; cf. L. ham...
1      aard-vark     Aard"-vark`, n. Etym: [D., earth-pig.] (Zoöl.)
2      aard-wolf     Aard"-wolf`, n. Etym: [D, earth-wolf] (Zoöl.)

当我直接说出这个词时,我会得到我想要的答案:

Blaze['Noun'] = np.where((Blaze['Info'].str.contains('n.')),True,False) Blaze['Verb'] = np.where((Blaze['Info'].str.contains('v.')),True,False)

       Word          Info                                                Noun   Verb
0      Aam           Aam, n. Etym: [D. aam, fr. LL. ama; cf. L. ham...   True   False
1      aard-vark     Aard"-vark`, n. Etym: [D., earth-pig.] (Zoöl.)      True   False
2      aard-wolf     Aard"-wolf`, n. Etym: [D, earth-wolf] (Zoöl.)       True   False

但这不可扩展,因为我要搜索 100 多个功能。

当我遍历列表 abbreviation 时:

abbreviation=['n'., 'v.']
col_name=['Noun','Verb']

for i in range(len(abbreviation)):
    Blaze[col_name[i]] = np.where((Blaze['Info'].str.contains(abbreviation[i])), True, False)

我返回的 DataFrame 中充满了“FALSE”条目:

       Word          Info                                                Noun   Verb
0      Aam           Aam, n. Etym: [D. aam, fr. LL. ama; cf. L. ham...   False  False
1      aard-vark     Aard"-vark`, n. Etym: [D., earth-pig.] (Zoöl.)      False  False
2      aard-wolf     Aard"-wolf`, n. Etym: [D, earth-wolf] (Zoöl.)       False  False

我可以看到几个类似的答案,但将答案分组在一行中: Check if each row in a pandas series contains a string from a list using apply?

Scalable solution for str.contains with list of strings in pandas

但我认为这些不能解决上述问题。

有人能解释我怎么错了吗?

【问题讨论】:

  • 您的代码对我有用——您唯一需要做的就是传递regex=False as. 是一个正则表达式字符,这意味着第二行将是True,因为有一个@987654334 @ 在里面。您执行循环的方式没有任何问题,但我认为我的方式可能稍微更pythonic。

标签: python pandas numpy


【解决方案1】:

您可以使用zip 同时遍历列表。确保将regex=False 传递给str.contains,因为. 是一个正则表达式字符。

abbreviation=['n.', 'v.']
col_name=['Noun','Verb']
for a, col in zip(abbreviation, col_name):
    Blaze[col] = np.where(Blaze['Info'].str.contains(a, regex=False),True,False)
Blaze
Out[1]: 
        Word                                               Info  Noun   Verb
0        Aam  Aam, n. Etym: [D. aam, fr. LL. ama; cf. L. ham...  True  False
1  aard-vark     Aard"-vark`, n. Etym: [D., earth-pig.] (Zoöl.)  True  False
2  aard-wolf      Aard"-wolf`, n. Etym: [D, earth-wolf] (Zoöl.)  True  False

如果需要,str.contains 也有一个case 参数,因此您可以指定case=False 进行不区分大小写的搜索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2019-04-11
    相关资源
    最近更新 更多