【问题标题】:Categorize a column using a Dictionary key - multiple values pair使用字典键对列进行分类 - 多值对
【发布时间】:2019-08-06 23:53:11
【问题描述】:

我有一本字典:

'Consulting': {'Deloitte', 'EY', 'KPMG', 'PwC'},
'Education': {'.edu', 'College', 'University'},
'Government':{'state','.gov','city'},
'Corporate':{'corpor','consumer','care'},
 ...... etc.

我有一个数据框:

 Sno  Text            column1    column2 ......
  1   Deloitte.com
  2   Texas.gov
  3   smi@EY.com
  4   UTD.edu
  5   rapper@corporate.com

 ..... etc.

我想用字典对数据框进行分类,并建立一个列Category,像这样:

 Sno  Text                   Category       column1    column2 ......
  1   Deloitte.com           Consulting
  2   Texas.gov              Government
  3   smi@EY.com             Consulting
  4   UTD.edu                Education
  5   rapper@corporate.com   Corporate
 ..... etc.

如何在 python 中使用具有多个值的字典在 Text 列中找到完整的短语或部分短语并对其进行分类?如果存在 2 个匹配项,我们是否也可以使用相同的逻辑?那会发生什么?

另外, 可能听起来很模糊,但我使用 Dictionary 的原因是因为我们可以将多个值映射到一个类别,有没有更好的方法可以在没有字典的情况下做到这一点?

【问题讨论】:

  • [k for k, v in dictionary.items() if v in col_value] 应该得到所有的匹配。假设只存在一个匹配,获取第 0 个索引。然后你可以使用 df[“text”].apply(lambda ...)。原谅错别字 - 我在用手机

标签: python pandas numpy dictionary logic


【解决方案1】:

IIUC 在重新创建dict 后使用findall,然后将其映射回来

newdict = {i: k for k, v in d.items() for i in v}
df.Text.str.findall('|'.join(newdict.keys())).str[0].map(newdict)
Out[431]: 
0    Consulting
1    Government
2    Consulting
3     Education
4     Corporate
Name: Text, dtype: object

df['cate']=df.Text.str.findall('|'.join(newdict.keys())).str[0].map(newdict)

【讨论】:

  • 您可以编辑代码以查找通配符吗?例如,我们有公司而不是公司,我仍然想将其标记为公司。 “.str.contains()”中的一些东西
  • @KshitijYadav 这涉及自然语言过程,您可能需要在真实数据中找到您的缩写类型
  • 知道了。最后一个问题,当名字满足两个条件的时候呢?就像它有corporate.edu 一样,这意味着它同时满足Corporate 和Education 的条件。我们将如何处理
  • @KshitijYadav[newdict[y] for y in x ]for x in df.Text.str.findall('|'.join(newdict.keys()))]
  • 如果我们想将那些“未找到”的行归类为“其他”会发生什么?
【解决方案2】:

这也可以使用renp.vectorize 来完成:

cat = re.compile('|'.join(f"(?P<{k}>{'|'.join(v)})" for k,v in categories.items()))
df['category'] = np.vectorize(lambda x: cat.search(x).lastgroup)(df.text)

这给了我:

                   text    category
0          Deloitte.com  Consulting
1             Texas.gov  Government
2            smi@EY.com  Consulting
3               UTD.edu   Education
4  rapper@corporate.com   Corporate

基本上,我创建了一个正则表达式字符串,其中包含类别字典键作为组名,值作为由| 分隔的模式意思是or。然后使用 vectorize 将此正则表达式搜索映射到每个项目,以获取找到的对应组名称

【讨论】:

  • 嘿,Jab,如果名字满足两个条件呢?就像它有corporate.edu 一样,这意味着它同时满足Corporate 和Education 的条件。我们将如何处理
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多