首页 > 解决方案 > 如何获取一列中每个元素的长度

问题描述

在 csv 文件中,有一列名为“no_pun”。其中有一些标记化的单词。我想获取此列中每个元素的长度。这在 python 中很容易。但我有一个错误。

我的代码:

for i in range(0,len(data['no_pun'])):
    data["len_desc"][i] = len(data["no_pun"][i])

关键错误:

  KeyError Traceback (most recent call last)
/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2655             try:
-> 2656                 return self._engine.get_loc(key)
   2657             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

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: 'len_desc'

在处理上述异常的过程中,又出现了一个异常:

标签: pythonpandas

解决方案


这将向现有数据框添加一个新列,该列具有来自no_pun列的字符串的长度:

data['NewColumnName'] = [len(x) for x in data['no_pun']]

或者

data['no_pun'].str.len()

推荐阅读