0

i have a Dataframe in panda with an index = Country names

i want to create a column continent

DF['Continent'] = DF['Country'].apply(lambda x: ContinentDict[x])

but i can't as country is an index. is there a similar solution?

all i do for now is something like this:

DF['Continent']= Top15.index #gets the country name
DF['Continent']= DF['Continent'].apply(lambda x: ContinentDict[x])

but i feel it's ugly

Edit:

I also tried

Top15['Continent']=[ContinentDict[x] for x in Top15.index]

but i feel it's really nasty also

Thank you for you help

1 Answer 1

1

You can reset the index for the purpose of the transformation:

DF.reset_index()['Country'].apply(lambda x: ContinentDict[x])

The cleanest approach, however, is to use the .replace method:

DF.reset_index()['Country'].replace(ContinentDict)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, why is it replace? for perf?
apply/lambda is not a pandas operation and often leads to inferior performance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.