0

I have a function I want to use to generate a new column

 def airport_to_country(a_code,country_dict):
     return country_dict[a_code]

Dataframe looks like this:

Rank  AirportCode
1   LAX
2   AUH
3   HBE
...
.

What I want to do I create another column so it would look like this

Rank  ACode  Country
1       LAX  North America
2       AUH  United Arab Emirates
3       HBE  Egypt
...
.

normally I would do this :

df['Country'] = df['Acode'].apply(airport_to_country))

But my function has 2 inputs, so I also need to give it the country_dict which is a Airport code to Country mapping

I was hoping this would work but its erroring as its looking for another input for the country

df['Country'] = df['Acode'].apply(airport_to_country(country_dict))

I looked at this example: Applying function with multiple arguments to create a new pandas column

But my function is a lookup in a dict and not a simple multiplication of variables. So I couldn't get it work

1 Answer 1

1

after some fiddling around I got it to work using that example:

df['country'] = df.apply(lambda x: airport_to_contry(x['a_code'],country_dict),axis = 1)
Sign up to request clarification or add additional context in comments.

4 Comments

df['a_code'].apply(airport_to_country, args=(country_dict,)) <-- The apply can be simplified to this.
Also, df['a_code'].apply(airport_to_country, country_dict=country_dict)
@ScottBoston just curious what does country_dict=country_dict do?
Passes externally define country_dict to the applied function as an argument for country_dict variable input.

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.