简体   繁体   中英

pandas apply function with multiple inputs to create a new column

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

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)

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