简体   繁体   中英

How do I create new columns to a dataframe using lambdas?

I would like to create 3 new columns in this dataframe:

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 )

Shouldn't that work? I get this error:

KeyError: 'CAMPAIGNID'

I've verified and the column CAMPAIGNID exists.

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()

How do I assign these 3 lambdas to calculate these new 3 columns?

For me working omit loop and use:

df = df.assign( **columnList )

for avoid KeyError s is possible convert columns to list, maybe some traling wtispaces problem:

print (df.columns.tolist())

and for remove whitespaces in columns names use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM