【问题标题】:Calculate word frequency in DataFrame计算DataFrame中的词频
【发布时间】:2015-10-23 05:43:30
【问题描述】:

我正在尝试创建一个数据框,其中第一列(“值”)在每一行中都有一个多字字符串,所有其他列的标签代表“值”中所有字符串中的唯一单词。我想用每个字符串(一行)的词频填充这个数据框,检查所有唯一的词(列)。从某种意义上说,创建一个简单的 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)

我不知道出了什么问题,感谢您的帮助 此外,如果有更简洁的方法来做到这一点(除了没有文本挖掘 - 安装问题),那将是很好的学习!

【问题讨论】:

    标签: python pandas indexing dataframe term-document-matrix


    【解决方案1】:

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

    testDF[irow, col]
    

    您的意思不是索引数据框中的单元格,以irow 作为索引,col 作为列,您不能为此使用简单的下标。您应该使用 .iloc 或类似的。示例 -

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

    如果您打算将irow 用于索引的0 索引编号,请使用.iloc,如果irow 是DataFrame 的确切索引,则可以使用.loc 而不是.iloc

    【讨论】:

    • .iloc 的工作就像轻而易举!对 Python 仍然很陌生,并且一直忘记对数据框元素的访问与对 pd.arrays 的访问不同:)
    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2015-01-07
    • 2019-04-19
    相关资源
    最近更新 更多