我在一个循环操作中生成了一个列表。在每个循环中,如果我打印列表,我会得到这样的结果:
[('E', 5), ('B', 3), ('C', 2)]
[('B', 5), ('D', 3), ('C', 2), ('A', 1), ('E', 7)]我有一个空的dataframe,列为A、B、C、D、E。
如何将生成的列表作为与列名匹配的行插入到数据帧中。在每个循环中生成的列表可能不具有所有列的值。需要替换为0的。
代码:
for document in myCorpus:
transform = tfidfCategory.transform([document])
for value in document.split():
score[value] = transform[0, tfidfCategory.vocabulary_[value]]
scoreValue = sorted(score.items(), key=operator.itemgetter(1), reverse=True)
print ("\t", scoreValue)
print()以上代码的输出:
[('E', 5), ('B', 3), ('C', 2)]
[('B', 5), ('D', 3), ('C', 2), ('A', 1), ('E', 7)]所需的输出数据帧:
A B C D E
0 3 2 0 5
1 5 2 3 7 请帮帮我!
问候Sudeep
发布于 2019-10-10 02:26:05
IIUC,你可以在列表理解上尝试concat:
scoreValue = [[('E', 5), ('B', 3), ('C', 2)],
[('B', 5), ('D', 3), ('C', 2), ('A', 1), ('E', 7)]]
pd.concat([pd.DataFrame(s).set_index(0).T for s in scoreValue], sort=True)输出:
A B C D E
1 NaN 3 2 NaN 5
1 1.0 5 2 3.0 7https://stackoverflow.com/questions/58309953
复制相似问题