首页 > 解决方案 > 如何使用 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 列?

标签: python-3.xpandasdictionarydataframe

解决方案


对我来说,省略循环并使用:

df = df.assign( **columnList )

为了避免KeyErrors 可以将列转换为列表,也许是一些 traling wtispaces 问题:

print (df.columns.tolist())

并删除列名中的空格,请使用:

df.columns = df.columns.str.strip()

推荐阅读