我正在尝试创建一个数据框,其中第一列(“Value”)在每一行中都有一个多字字符串,所有其他列的标签代表“Value”中所有字符串的唯一单词。我想用每个字符串(一行)的词频填充这个数据框,检查所有唯一的词(列)。从某种意义上说,创建一个简单的 TDM
rows = ['you want peace', 'we went home', 'our home is nice', 'we want peace at home']
col_list = [word.lower().split(" ") for word in rows]
set_col = set(list(itertools.chain.from_iterable(col_list)))
columns = set_col
ncols = len(set_col)
testDF = pd.DataFrame(columns = set_col)
testDF.insert(0, "Value", " ")
testDF["Value"] = rows
testDF.fillna(0, inplace=True)
irow = 0
for tweet in testDF["Value"]:
for word in tweet.split(" "):
for col in xrange(1, ncols):
if word == testDF.columns[col]: testDF[irow, col] += 1
irow += 1
testDF.head()
但是,我收到一个错误:
KeyError Traceback (most recent call last)
<ipython-input-64-9a991295ccd9> in <module>()
23 for col in xrange(1, ncols):
24
---> 25 if word == testDF.columns[col]: testDF[irow, col] += 1
26
27 irow += 1
C:\Users\Tony\Anaconda\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key)
1795 return self._getitem_multilevel(key)
1796 else:
-> 1797 return self._getitem_column(key)
1798
1799 def _getitem_column(self, key):
pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:3824)()
pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:3704)()
pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12280)()
pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12231)()
KeyError: (0, 9)
我不确定出了什么问题,将感谢您的帮助此外,如果有更清洁的方法可以做到这一点(除了没有文本挖掘 - 安装问题),学习会很棒!