我保存了一个大文件,其中包含单词/标签对,如下所示:
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/