python - 匹配 Pandas 列列表中的单词并分配分数

标签 python pandas list

我有以下两个数据集 - 一个包含文本的数据集:

text = {'Text':[['Nike', 'invests', 'in', 'shoes'], ['Adidas', 'invests', 'in',  't-shirts']]}
text_df = pd.DataFrame(text)
text_df

以及包含单词以及相应分数和主题的数据集。

points = {'Text':['invests', 'shoes', 'Adidas'], 'Score':[1, 2, 1], 'Topic':['not_name', 'not_name', 'name' ] }
points_df = pd.DataFrame(points)
points_df

对于文本数据集中的每一行,我想看看这个词是否存在,如果这个词存在, 创建一个以类别命名的列,并创建一个包含相关词得分的新列表。如果单词不存在,请分配一个零。

这是结果

text_results = {'Text':[['Nike', 'invests', 'in', 'shoes'], ['Adidas', 'invests', 'in',  't-shirts']], 'not_name': [[0, 1, 0, 2], [0, 1, 0, 0]], 'name': [[0, 0, 0, 0], [1, 0, 0, 0]]}
results_df = pd.DataFrame(text_results)
results_df

有什么建议吗?我有点迷路了!

最佳答案

首先是 points_df 中的值,按 DataFrame.pivot_table 旋转, 用 DataFrame.to_dict 替换缺失值并创建字典:

df1 = points_df.pivot_table(index='Text',
                            columns='Topic',
                            values='Score', 
                            fill_value=0, 
                            aggfunc='sum')
d = df1.to_dict('index')
print (d)
{'Adidas': {'name': 1, 'not_name': 0}, 
 'invests': {'name': 0, 'not_name': 1}, 
 'shoes': {'name': 0, 'not_name': 2}}

从列名称创建字典,填充0 值用于不存在的值:

missd = dict.fromkeys(df1.columns, 0)
print (missd)
{'name': 0, 'not_name': 0}

然后 text_df['Text'] 中列表的每个值都是由 dict.get 映射的值,所以如果没有匹配可能使用默认缺失值字典:

L = [[d.get(y, missd) for y in x] for x in text_df['Text']]

然后由 this solution 将格式从字典列表更改为列表理解中的列表字典:

L = [{k: [dic[k] for dic in x] for k in x[0]} for x in L]
print (L)
[{'name': [0, 0, 0, 0], 'not_name': [0, 1, 0, 2]}, 
 {'name': [1, 0, 0, 0], 'not_name': [0, 1, 0, 0]}]

最后创建 DataFrame 并添加到 text_df:

df = text_df.join(pd.DataFrame(L, index=text_df.index))
print (df)
                              Text          name      not_name
0       [Nike, invests, in, shoes]  [0, 0, 0, 0]  [0, 1, 0, 2]
1  [Adidas, invests, in, t-shirts]  [1, 0, 0, 0]  [0, 1, 0, 0]

关于python - 匹配 Pandas 列列表中的单词并分配分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62187437/

相关文章:

java - 如何迭代 arrayList 中的连续对

python - 通过每个项目的两个第一个值优化列表列表中的频率

python - 子类化 datetime64

python - 按下按键时 pygame 继续循环

python - 将 Python 列表变量复制到现有 xlsx excel 文件中

python - LabelEncoder vs. Pandas 分类 vs. 枚举?

python - 取行中不带标签的数值,正则表达式

python - Matplotlib tick.get_loc() 始终返回零

python - Django 可重用应用程序配置

javascript - 按字母顺序排列项目列表