1

我正在尝试创建一个数据框,其中第一列(“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)

我不确定出了什么问题,将感谢您的帮助此外,如果有更清洁的方法可以做到这一点(除了没有文本挖掘 - 安装问题),学习会很棒!

4

1 回答 1

2

我不是 100% 确定您的完整程序正在尝试做什么,但如果通过以下方式 -

testDF[irow, col]

您的意思不是索引数据框中的单元格,irow作为索引和col列,您不能使用简单的下标。你应该代替使用.iloc等。例子 -

 if word == testDF.columns[col]: testDF.iloc[irow, col] += 1

.iloc如果您打算使用irowindex 的 0 索引编号,如果irow是 DataFrame 的确切索引,则可以使用.loc代替.iloc.

于 2015-10-23T05:50:01.310 回答