python - 从对中创建 pandas 数据框的快速方法

标签 python pandas tags

我保存了一个大文件,其中包含单词/标签对,如下所示:

This/DT gene/NN called/VBN gametocide/NN

现在我想将这些对放入 DataFrame 中,其计数如下:

      DT | NN --
This|  1   0
Gene|  0   1
 :

我尝试使用一个字典来计算对的数量,然后将其放入 DataFrame 中:

file = open("data.txt", "r")

train = file.read()
words = train.split()

data = defaultdict(int)
for i in words:
    data[i] += 1

matrixB = pd.DataFrame()

for elem, count in data.items():
    word, tag = elem.split('/')
    matrixB.loc[tag, word] = count

但这需要很长时间(文件大约有 300000 个)。有没有更快的方法来做到这一点?

最佳答案

your other question 的答案有什么问题吗? ?

from collections import Counter

with open('data.txt') as f:
    train = f.read()
c = Counter(tuple(x.split('/')) for x in train.split())
s = pd.Series(c)
df = s.unstack().fillna(0)

print(df)

产量

            DT  NN  VBN
This         1   0    0
called       0   0    1
gametocide   0   1    0
gene         0   1    0

关于python - 从对中创建 pandas 数据框的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35729716/

相关文章:

python - 类方法包装函数-参数问题

python - 按 pandas 中的列名重新分类

python - 分组行 python pandas

algorithm - 词干提取——代码示例还是开源项目?

python - 在 matplotlib python 中以 3D 形式动画绘制两种不同的颜色和形状

python - Kivy (Python) TabbedPanel - 不同(动态)大小的选项卡?

python - eyed3 for python - 如何从音频文件加载选择性 id3 数据?

azure - 需要仅为 VM 的标签部署 Azure 策略

Python > Uncompyle2 - 用法

python - Pandas 在循环中合并数据帧