【问题标题】:How do I create new columns to a dataframe using lambdas?如何使用 lambdas 为数据框创建新列?
【发布时间】:2018-05-10 05:41:47
【问题描述】:

我想在这个数据框中创建 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 个新列?

【问题讨论】:

  • print (df.columns.tolist()) 是什么?
  • 你能分享一小部分你试图应用它的数据框吗?以及您希望输出数据框看起来像什么的示例?这将有助于提供更多的上下文
  • 谢谢! @the_martian 我试图创建新的 True/False 列,以指示这些列是否具有值:CAMPAIGNID、LEADTYPE、EVENT。这是数据框:['ID', 'AMOUNT', 'CAMPAIGNID', 'LEADTYPE', 'EVENT', 'STARTDATE', 'DISCOUNTAMOUNT', 'DISCOUNTAPPROVED'] 谢谢@jezrael!这段代码成功了:df = df.assign( **columnList )

标签: python-3.x pandas dictionary dataframe


【解决方案1】:

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

df = df.assign( **columnList )

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

print (df.columns.tolist())

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

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

【讨论】:

  • 谢谢!那解决了! df = df.assign( **columnList )
猜你喜欢
  • 2017-04-16
  • 1970-01-01
  • 2019-08-29
  • 1970-01-01
  • 2019-01-13
  • 2022-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多