python - 使用 numpy 或 pandas 从元组列表中为二元组创建频率矩阵
问题描述
我对 Python 很陌生。我有一个元组列表,我在其中创建了二元组。
这个问题非常接近我的需求
my_list = [('we', 'consider'), ('what', 'to'), ('use', 'the'), ('words', 'of')]
现在我正在尝试将其转换为频率矩阵
所需的输出是
consider of the to use we what words
consider 0 0 0 0 0 0 0 0
of 0 0 0 0 0 0 0 0
the 0 0 0 0 0 0 0 0
to 0 0 0 0 0 0 0 0
use 0 0 1 0 0 0 0 0
we 1 0 0 0 0 0 0 0
what 0 0 0 1 0 0 0 0
words 0 1 0 0 0 0 0 0
如何做到这一点,使用numpy
or pandas
?nltk
不幸的是,我只能看到一些东西。
解决方案
如果您不太关心速度,则可以使用 for 循环。
import pandas as pd
import numpy as np
from itertools import product
my_list = [('we', 'consider'), ('what', 'to'), ('use', 'the'), ('words', 'of')]
index = pd.DataFrame(my_list)[0].unique()
columns = pd.DataFrame(my_list)[1].unique()
df = pd.DataFrame(np.zeros(shape=(len(columns), len(index))),
columns=columns, index=index, dtype=int)
for idx,col in product(index, columns):
df[col].loc[idx] = my_list.count((idx, col))
print(df)
输出:
consider to the of
we 1 0 0 0
what 0 1 0 0
use 0 0 1 0
words 0 0 0 1
推荐阅读
- typescript - 如何创建类型安全的高阶 Redux 动作创建者?
- c# - System.DivideByZeroException: '试图除以零。'
- android - 使用 smalidea 在 Intellij 调试器中调试 smali 代码时访问虚拟寄存器
- ionic2 - 我无法使用来自 ios 的 facebook 验证 myapp
- r - 如何构造amxm相关矩阵
- android - Android Studio 的 logcat 在具有 Lollipop(5.1) 的 Gionee P5W 中运行应用程序时显示“Error inflating class EditText”
- regex - 如何分离正则表达式并获得每一次出现?
- qt - 如何在代码片段中获取当前文件名
- python - 如何在 softmax 分数中添加阈值
- python-2.7 - 将 Python(2.7) 字典转换为有效的查询参数