python - 如何获取一列中每个元素的长度
问题描述
在 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'
在处理上述异常的过程中,又出现了一个异常:
解决方案
这将向现有数据框添加一个新列,该列具有来自no_pun
列的字符串的长度:
data['NewColumnName'] = [len(x) for x in data['no_pun']]
或者
data['no_pun'].str.len()
推荐阅读
- python - 如果元素不等于另一个列表中的元素,则从列表中删除每个第 n 个元素?
- javascript - 为什么 useState 不应用新值
- javascript - 如何将嵌套对象的值转移到更高级别,然后删除该对象?- javascript
- python - 我无法用 python 将我的不和谐机器人连接到我的代码
- javascript - 如何要求反应应用程序中的图像列表
- python - ImportError:尝试升级 pip 后没有名为 pip 的模块
- android - 这个崩溃注册了很多次 - java.lang.RuntimeException: at android.view.DisplayListCanvas.throwIfCannotDraw
- xamarin - Xamarin MVVMCross:注册具有多个接口的类的单例
- node.js - npm 安装失败,npm 错误!无效的 json 响应
- woocommerce - Woccommerce 订阅定期付款问题