使用字典计算python数据框中的单词频率

时间:2018-12-04 02:30:54

标签: python pandas dictionary dataframe count

我有一个由文本工作描述和3个空列组成的数据框

   index   job_description                 level_1      level_2        level_3
    0      this job requires masters in..    0             0              0
    1      bachelor degree needed for..      0             0              0
    2      ms is preferred or phd..          0             0              0

我试图遍历每个工作描述字符串,并计算工作描述中提到的每个学位级别的频率。示例输出应如下所示。

   index   job_description                 level_1      level_2        level_3
    0      this job requires masters in..    0             1              0
    1      bachelor degree needed for..      1             0              0
    2      ms is preferred or phd..          0             1              1

我创建了字典来进行比较,如下所示,但是我对如何在数据框“工作描述”列的字符串中查找那些单词以及如何根据这些单词是否填充数据框列一无所知存在与否。

my_dict_1 = dict.fromkeys(['bachelors', 'bachelor', 'ba','science
                           degree','bs','engineering degree'], 1)
my_dict_2 = dict.fromkeys(['masters', 'ms', 'master'], 1)
my_dict_3 = dict.fromkeys(['phd','p.h.d'], 1)

我非常感谢对此的支持。

3 个答案:

答案 0 :(得分:2)

这样的事情怎么样?

由于三个字典中的每一个都对应于您要创建的不同列,因此我们可以创建另一个字典映射,将即将成为列的名称作为键,并将要在每个特定级别搜索的字符串作为值(实际上,您甚至不需要字典来存储my_dict_<x>项-您可以使用set-但这没什么大不了的):

>>> lookup = {'level_1': my_dict_1, 'level_2': my_dict_2, 'level_3': my_dict_3}
>>> lookup
{'level_1': {'bachelors': 1, 'bachelor': 1, 'ba': 1, 'science degree': 1, 'bs': 1, 'engineering degree': 1}, 'level_2': {'masters': 1, 'ms': 1, 'master': 1}, 'level_3': {'phd': 1, 'p.h.d': 1}}

然后,遍历刚创建的词典中的每个建议列,并分配一个新列,该列创建所需的输出,检查每个my_dict_<x>对象中指定的每个级别,是否至少有一个属于工作描述在每一行中...

>>> for level, values in lookup.items():
...     df[level] = df['job_description'].apply(lambda x: 1 if any(v in x for v in values) else 0)
... 
>>> df
              job_description  level_1  level_2  level_3
0     masters degree required        0        1        0
1  bachelor's degree required        1        0        0
2    bachelor degree required        1        0        0
3                phd required        0        0        1

另一种解决方案,使用scikit-learn的CountVectorizer类,该类对出现在字符串中的记号(基本上是单词)的频率进行计数:

>>> from sklearn.feature_extraction.text import CountVectorizer

指定特定的词汇-忘记所有不是“学术证书”关键字的其他单词:

>>> vec = CountVectorizer(vocabulary={value for level, values in lookup.items() for value in values})
>>> vec.vocabulary
{'master', 'p.h.d', 'ba', 'ms', 'engineering degree', 'masters', 'phd', 'bachelor', 'bachelors', 'bs', 'science degree'}

将该转换器设置为可迭代的文本df['job_description']

>>> result = vec.fit_transform(df['job_description'])

深入了解结果:

>>> pd.DataFrame(result.toarray(), columns=vec.get_feature_names())
   ba  bachelor  bachelors  bs  engineering degree  master  masters  ms  p.h.d  phd  science degree
0   0         0          0   0                   0       0        1   0      0    0               0
1   0         1          0   0                   0       0        0   0      0    0               0
2   0         1          0   0                   0       0        0   0      0    0               0
3   0         0          0   0                   0       0        0   0      0    1               0

如果您想回到自己的level_<x>列结构,则最后一种方法可能需要做更多的工作,但是我想我只是将它展示为一种不同的思考方式来编码这些数据点。

>

答案 1 :(得分:2)

一种略有不同的方法是将关键字和职位描述存储为集合,然后计算集合相交。您可以通过向量set.intersection紧凑地生成交集矩阵:

import pandas as pd

df = pd.read_csv(
    pd.compat.StringIO(
        """   index   job_description                 level_1      level_2        level_3
        0      this job requires masters in..    0             0              0
            1      bachelor degree needed for..      0             0              0
                2      ms is preferred or phd ..          0             0              0"""
    ),
    sep=r"  +",
)


levels = pd.np.array(
    [
        {"bachelors", "bachelor", "ba", "science degree", "bs", "engineering degree"},
        {"masters", "ms", "master"},
        {"phd", "p.h.d"},
    ]
)

df[["level_1", "level_2", "level_3"]] = (
    pd.np.vectorize(set.intersection)(
        df.job_description.str.split().apply(set).values[:, None], levels
    )
    .astype(bool)
    .astype(int)
)

   index                 job_description  level_1  level_2  level_3
0      0  this job requires masters in..        0        1        0
1      1    bachelor degree needed for..        1        0        0
2      2       ms is preferred or phd ..        0        1        1

答案 2 :(得分:1)

我认为我们可以这样做:

# create a level based mapper dict
mapper = {'level_1':['bachelors', 'bachelor', 'ba','science degree','bs','engineering degree'],
          'level_2': ['masters', 'ms', 'master'],
          'level_3': ['phd','p.h.d']}

# convert list to set
mapper = {k:set(v) for k,v in mapper.items}

# remove dots from description
df['description'] = df['description'].str.replace('.','')

# check if any word of description is available in the mapper dict
df['flag'] = df['description'].str.split(' ').apply(set).apply(lambda x: [k for k,v in mapper.items() if any([y for y in x if y in v])])

# convert the list into new rows
df1 = df.set_index(['index','description'])['flag'].apply(pd.Series).stack().reset_index().drop('level_2', axis=1)
df1.rename(columns={0:'flag'}, inplace=True)

# add a flag column , this value will be use as filler
df1['val'] = 1

# convert the data into wide format
df1 = df1.set_index(['index','description','flag'])['val'].unstack(fill_value=0).reset_index()
df1.columns.name = None

print(df1)

   index                   description  level_1  level_2  level_3
0      0  this job requires masters in        0        1        0
1      1  bachelor degree needed for 0        1        0        0
2      2        ms is preferred or phd        0        1        1