3

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

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.