在datafram中插入循环列表

2024-09-28 05:15:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

[('E', 5), ('B', 3), ('C', 2)]


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

我有一个空的数据帧,列为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  

请帮帮我!你知道吗

敬礼 苏迪普


Tags: 数据代码in列表forvaluetransformdocument
2条回答

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  7
a_list=[('E', 5), ('B', 3), ('C', 2)]

new_row = pd.Series()

map = {"A": 0, "B": 0, "C": 0, "D":0, "E":0}

for a in a_list:
    map[a[0]] =a[1]
new_row = pd.Series(map)
df = df.append(new_row, ignore_index=True)

因此,我们将映射初始化为0,然后在映射中填充所需的值。使用它创建新行并在df中追加。 你需要为每个列表创建一个新的映射。你知道吗

相关问题 更多 >

    热门问题