[英]How to convert list of word counts into dataframe for sentiment analysis
我有一个看起来像这样的 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)
但我没有在我的数据中看到 class 列,并且我为同一个单词获得了多个列。
它们是字典,而不是列表对象。
你需要用字典列出一个列表:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.