python - 将字典中的值转换为矩阵
问题描述
我计算了一个单词在文本文档中出现的次数,并将这些值放入字典中。现在我想将这些数量添加到一个矩阵中,该矩阵由作为列的文本文件和作为行的不同单词组成。这是字典的输出:
{'test1.txt': {'peer': 1, 'appel': 1, 'moes': 1},
'test2.txt': {'peer': 1, 'appel': 1},
'test3.txt': {'peer': 1, 'moes': 2},
'test4.txt': {'peer': 1, 'moes': 1, 'ananas': 1}}
矩阵的输出必须如下所示:
[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'],
['moes', 1, 0, 2, 1],
['appel', 1, 1, 0, 0],
['peer', 1, 1, 1, 1],
['ananas', 0, 0, 0, 1]]
这是我现在用来打印矩阵的代码,但是一个单词在每个文档中出现的次数还没有实现。
term_freq_matrix = []
list_of_files.insert(0," ")
term_freq_matrix.insert(1, list_of_files)
for unique_word in unique_words:
unique_word = unique_word.split()
term_freq_matrix.append(unique_word)
print(term_freq_matrix)
谢谢!
解决方案
与熊猫:
import pandas as pd
df = pd.DataFrame(d).fillna(0) #d is your dictionary
result = [[''] + df.columns.to_numpy().tolist()]+ df.reset_index().to_numpy().tolist()
print(result)
输出
[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'],
['ananas', 0.0, 0.0, 0.0, 1.0],
['appel', 1.0, 1.0, 0.0, 0.0],
['moes', 1.0, 0.0, 2.0, 1.0],
['peer', 1.0, 1.0, 1.0, 1.0]]
推荐阅读
- python - 在某些条件下从 numpy 数组中删除特定值
- .net - ASP.NET MVC 在发布到服务器时自动更改连接字符串
- javascript - 使用所有函数参数而不必枚举它们
- php - 组合来自不同 MySQL 条目的数组并删除重复项
- tomcat - 如何在 Tomcat 9 中创建自定义类路径?
- c - 我可以在 C 程序中同时打开多少个临时文件?
- amazon-redshift - Redshift Dist 键、IDentity 列或连接列?列的基数,用于排序键的联接考虑
- c# - Xpath 为正统的孩子
- swift - 领域对象添加后返回 nil
- javascript - 如何将一个数组元素与其各自的下一个数组元素交换并显示输出?