Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError using apply function

Tags:

pandas

I have a data frame with the following columns, and I'm simply trying to add a new column by transforming an existing one. I don't understand why I get this error, especially given is that the data frame is fine and I can groupby on Zip without any index problems.

print(df.columns)

# Index(['First Col', 'Year', 'Submitted', 'Allowed', 'Provided', 'X', 'Zip'],
# dtype='object')

print(df['Zip'])

# 0       10523
# 1       11803
# 2       22939
# 3       21742
# 4       21801
# 5       21804
# ...

df['NEW'] = df.apply(lambda row: cool_fn(row['Zip']))
KeyError: ('Zip', 'occurred at index First Col')
like image 931
chris Avatar asked May 20 '26 11:05

chris


1 Answers

For processing per rows is necessary add axis=1 to DataFrame.apply:

df['NEW'] = df.apply(lambda row: cool_fn(row['Zip']), axis=1)

Or use Series.apply, then lambda should be omit:

df['NEW'] = df['Zip'].apply(cool_fn)
like image 70
jezrael Avatar answered May 23 '26 11:05

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!