首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将循环列表插入到pandas数据帧中

将循环列表插入到pandas数据帧中
EN

Stack Overflow用户
提问于 2019-10-10 02:11:25
回答 2查看 558关注 0票数 0

我在一个循环操作中生成了一个列表。在每个循环中,如果我打印列表,我会得到这样的结果:

代码语言:javascript
运行
复制
[('E', 5), ('B', 3), ('C', 2)]


[('B', 5), ('D', 3), ('C', 2), ('A', 1), ('E', 7)]

我有一个空的dataframe,列为A、B、C、D、E。

如何将生成的列表作为与列名匹配的行插入到数据帧中。在每个循环中生成的列表可能不具有所有列的值。需要替换为0的。

代码:

代码语言:javascript
运行
复制
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()

以上代码的输出:

代码语言:javascript
运行
复制
[('E', 5), ('B', 3), ('C', 2)]
[('B', 5), ('D', 3), ('C', 2), ('A', 1), ('E', 7)]

所需的输出数据帧:

代码语言:javascript
运行
复制
A  B  C  D  E       
0  3  2  0  5        
1  5  2  3  7  

请帮帮我!

问候Sudeep

EN

Stack Overflow用户

发布于 2019-10-10 02:26:05

IIUC,你可以在列表理解上尝试concat

代码语言:javascript
运行
复制
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)

输出:

代码语言:javascript
运行
复制
     A  B  C    D  E
1  NaN  3  2  NaN  5
1  1.0  5  2  3.0  7
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58309953

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档