如何将列表插入 pandas dataframe 中的单元格

问题描述 投票:0回答:0

我已经提到了this 但它没有帮助。 请不要复制这个。我正在尝试为我的

syllable per word
目录中的每个文本文件计算
output
。我想为每个文件插入一个音节列表。

我的做法:

directory = r"..\output" 
result = []
i = 0
for filename in os.listdir(directory):
    if filename.endswith('.txt'):
        filepath = os.path.join(directory, filename)
    with open(filepath, 'rb') as f:
            encoding = chardet.detect(f.read())['encoding']
    with open(filepath, 'r', encoding=encoding) as f:
            text = f.read()
            words = text.split()
            for word in words:
                result.append(count_syllables(word))
    results.at[i,'SYLLABLE PER WORD'] = result
    i += 1

我收到以下错误:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3801             try:
-> 3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:

~\AppData\Roaming\Python\Python39\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

~\AppData\Roaming\Python\Python39\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'SYLLABLE PER WORD'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
~\AppData\Roaming\Python\Python39\site-packages\pandas\core\frame.py in _set_value(self, index, col, value, takeable)
   4209             else:
-> 4210                 icol = self.columns.get_loc(col)
   4211                 iindex = self.index.get_loc(index)

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3803             except KeyError as err:
-> 3804                 raise KeyError(key) from err
   3805             except TypeError:

KeyError: 'SYLLABLE PER WORD'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_19000\1445037766.py in <module>
     12             for word in words:
     13                 result.append(count_syllables(word))
---> 14     results.at[i,'SYLLABLE PER WORD'] = result
     15     i += 1

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexing.py in __setitem__(self, key, value)
   2440             return
   2441 
-> 2442         return super().__setitem__(key, value)
   2443 
   2444 

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexing.py in __setitem__(self, key, value)
   2395             raise ValueError("Not enough indexers for scalar access (setting)!")
   2396 
-> 2397         self.obj._set_value(*key, value=value, takeable=self._takeable)
   2398 
   2399 

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\frame.py in _set_value(self, index, col, value, takeable)
   4222                 self.iloc[index, col] = value
   4223             else:
-> 4224                 self.loc[index, col] = value
   4225             self._item_cache.pop(col, None)
   4226 

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexing.py in __setitem__(self, key, value)
    816 
    817         iloc = self if self.name == "iloc" else self.obj.iloc
--> 818         iloc._setitem_with_indexer(indexer, value, self.name)
    819 
    820     def _validate_key(self, key, axis: int):

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexing.py in _setitem_with_indexer(self, indexer, value, name)
   1748                             indexer, self.obj.axes
   1749                         )
-> 1750                         self._setitem_with_indexer(new_indexer, value, name)
   1751 
   1752                         return

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexing.py in _setitem_with_indexer(self, indexer, value, name)
   1793         if take_split_path:
   1794             # We have to operate column-wise
-> 1795             self._setitem_with_indexer_split_path(indexer, value, name)
   1796         else:
   1797             self._setitem_single_block(indexer, value, name)

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexing.py in _setitem_with_indexer_split_path(self, indexer, value, name)
   1848                     return self._setitem_with_indexer((pi, info_axis[0]), value[0])
   1849 
-> 1850                 raise ValueError(
   1851                     "Must have equal len keys and value "
   1852                     "when setting with an iterable"

ValueError: Must have equal len keys and value when setting with an iterable

我想迭代地将

syllables per word
的列表插入到数据框中,正如您从我的方法中看到的那样。

python machine-learning file-io nlp
© www.soinside.com 2019 - 2024. All rights reserved.