【问题标题】:How to convert list of word counts into dataframe for sentiment analysis如何将字数列表转换为数据框以进行情感分析
【发布时间】:2018-03-31 02:00:31
【问题描述】:

我有一个如下所示的 python 列表对象:

{'word1':#, 'word2':#, 'word3':#, 'class':'pos'}

{'word2':#, 'word4':#, 'word5':#, 'word6':#, 'class':'neg'}

其中每一行都有一个单词列表,以及文件中各行的单词数,最后一个列表项始终是 pos(正数)或 neg(负数)。 (这是用于情绪分析的)。

我正在尝试将其转换为数据框,其中每一列都是列表中每一行的所有可能单词。每行都有该项目的字数:

df:

row   word1   word2   word3   word4   word5   word6   class
1     #       #       #       0       0       0       pos
2     0       #       0       #       #       #       neg

我该怎么做?我尝试使用

直接将其转换为数据框
df = pd.DataFrame(list)

但我没有在我的数据中看到类列,并且我得到同一个单词的多个列。

【问题讨论】:

  • 似乎python字典不是列表

标签: python python-3.x pandas


【解决方案1】:

它们是字典,而不是列表对象。

你需要用字典做一个列表:

import pandas as pd

list = [{'word1':10, 'word2':34, 'word3':75, 'class':'pos'},
        {'word2':35, 'word4':53, 'word5':3, 'word6':59, 'class':'neg'}]

df = pd.DataFrame(data=list, index=range(1, len(list)+1))
print(df)

print() # Empty line

df = df.replace(pd.np.nan, "0") # Replace NaN values with 0s
print(df)

输出:

  class  word1  word2  word3  word4  word5  word6
1   pos   10.0     34   75.0    NaN    NaN    NaN
2   neg    NaN     35    NaN   53.0    3.0   59.0

  class word1  word2 word3 word4 word5 word6
1   pos    10     34    75     0     0     0
2   neg     0     35     0    53     3    59

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2013-04-02
    相关资源
    最近更新 更多