python-3.x - 如何使用 lambdas 为数据框创建新列?
问题描述
我想在这个数据框中创建 3 个新列:
columnList = { 'hasCampaign': ( lambda x: x[ 'CAMPAIGNID' ] != '' ),
'hasLeadType': ( lambda x: x[ 'LEADTYPE' ] != '' ),
'hasEvent': ( lambda x: x[ 'EVENT' ] != '' ) }
for ( k, v ) in columnList.items():
df = df.assign( k = v )
那不应该工作吗?我收到此错误:
KeyError: 'CAMPAIGNID'
我已经验证并且存在 CAMPAIGNID 列。
KeyError Traceback (most recent call last)
/usr/local/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
2524 try:
-> 2525 return self._engine.get_loc(key)
2526 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()
如何分配这 3 个 lambda 来计算这些新的 3 列?
解决方案
对我来说,省略循环并使用:
df = df.assign( **columnList )
为了避免KeyError
s 可以将列转换为列表,也许是一些 traling wtispaces 问题:
print (df.columns.tolist())
并删除列名中的空格,请使用:
df.columns = df.columns.str.strip()
推荐阅读
- node.js - 从 Azure Pipeline 步骤运行节点 shebang 脚本
- gradle - 在 Gradle 构建中无法获取 org.jetbrains.intellij 插件
- sql - 如何将 SQL 查询的结果保存在 Powershell 字符串变量中?
- firebase - Firebase 云功能模拟器在 30000 毫秒后超时
- python - 删除用点分隔的路径的一部分
- java - 访问根文件夹的 Java 代码获得访问被拒绝错误
- python - 即使在使用 for 循环后复制后列表也是空的
- python - 如何将函数应用于数据框列
- c# - 抛出错误的异常
- apache-camel - 自定义 Camel 组件 - 在 FTP 使用者中调用 FTP