【问题标题】:Pandas find exact words from a list and assign Boolean value if foundPandas 从列表中找到确切的单词,如果找到则分配布尔值
【发布时间】:2022-07-06 05:08:37
【问题描述】:

所以,我有这样的数据框,

data = {
  "properties": ["FinancialOffice","Gas Station", "Office", "K-12 School"],
}
df = pd.DataFrame(data)

这是我的清单,

proplist = ["Office","Other - Mall","Gym"]

我想要做的是使用列表,我试图找出哪些单词与数据框列完全匹配,并且对于数据框中的每个单词,我需要分配一个布尔真/假值或 0/1。它必须是完全匹配的。

这样的输出,

properties         flag
FinancialOffice    FALSE
Gas Station        FALSE
Office             TRUE
K-12 School        FALSE

因此,它仅对“Office”返回 TRUE,因为它与列表完全匹配。 FinancialOffice 不是因为它不在列表中。

这是我的方法,效果很好,但我需要为 df 分配一个新的布尔列以找出哪些是完全匹配的。

我的方法,

import re 
s= ','.join(df["properties"]) # gives comma separated values. 

for words in proplist  :
    if re.search(r'\b' + words + r'\b', s):
        print('{0}'.format(words)) ## print out only Office the matching word.

感谢任何帮助。它需要是正则表达式,因为 str.contains 找不到完全匹配。

【问题讨论】:

    标签: python regex pandas text-mining


    【解决方案1】:

    您可以将 map 与 lambda 一起使用:

    df['flag'] = df['properties'].map(lambda x: x in proplist)
    

    【讨论】:

      【解决方案2】:

      试试Series.isin:

      df["flag"] = df["properties"].isin(proplist)
      print(df)
      

      打印:

              properties   flag
      0  FinancialOffice  False
      1      Gas Station  False
      2           Office   True
      3      K-12 School  False
      

      【讨论】:

        猜你喜欢
        • 2020-10-07
        • 2022-12-04
        • 2017-09-07
        • 2017-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多