Python Pandas - Create column & add stings?

Soldato
Joined
7 Jan 2007
Posts
10,608
Location
Sussex, UK
Hi there,

I'm playing about with Python and pandas.

I have a column called 'County' but I need to create a column called 'Region' and populate it like this (atleast I think):

If County column == 'Suffolk' or 'Norfolk' or 'Essex' then in Region column insert 'East Anglia'

If County column == 'Kent' or 'East Sussex' or 'West Sussex' then in Region Column insert 'South East'

If County column == 'Dorset' or 'Devon' or 'Cornwall' then in Region Column insert 'South West'

So far I have this:

Code:
myDataFrame['Region'] = np.where(myDataFrame['County']=='Suffolk', 'East Anglia', '')

But I suspect this won't work for any other counties

As I'm sure is obvious I am a beginner.

Hope people can help a noob!
 
Caporegime
Joined
18 Oct 2002
Posts
32,618
use a Lambda function
Code:
def find_region(county):
   countyMap = {"'Suffolk": "East Anglia'" , "Norfolk":"East Anglia'","Kent":"South East"}  # Python doesn't have  a switch statement, this map might not be quite a efficient but it has a clean syntax.
   return countyMap[county]
       

df['Region'] = df.apply(lambda x: find_region(x['County']), axis=1)

Totally untested and may not have quite the right syntax but something like this should work.
 
Back
Top Bottom