0

I have a dataframe, df, in pandas with a column called 'Primary Sector - Org'. I also have a dictionary called dictionary. I want to replace elements of that column that are the values in my dictionary with the keys of the dictionary.

For example my dictionary looks like this:

dictionary = {
    "transport" : ['Transport', 'Transportation'],
    "buildings" :  ['Housing','Provision of Housing'],
    "energy" : ["Energy", "Energy; Housing; Income or financial inclusion"],
    "food" : ["Food catering or production (incl. farming)"],
    "waste and consumption" : ["Waste Reduction Re-use or Recycling", "Waste Reduction, Reuse or Recycling"],
    "natural envrionment" : ["Environmnet or nature", "Environmnet or Nature","Environmnet or Nature; Other", "Environmnet or nature conservation","Environmnet or nature conservation, Employmnet support or training", 
                             "Environment or Nature; Health Care or Wellbeing", "Horticulture"]
}

When the value of say "Environmnet or nature" appreas in the column, I want to replace it with "natural environment". How would I do this? I have have tried doing the following:

df['Primary Sector - Org'] = df.apply(lambda x: [dictionary[i] if i in dictionary else '' for i in x],axis=1)
df 

But that does not replace the elements correctly. Thanks so much if you could help :)

  • Given dictionary seems invalid, dictionaries can not have duplicated keys. In case of duplicated keys only the last key value pair will be preserved. – Shubham Sharma Apr 22 '21 at 12:34

1 Answers1

0

To begin, you can't have duplicate keys in your dict. Not only is having two keys of "transport" counterproductive and unnecessary, but the second transport will simply override the first one.

Additionally, your code is very disorganized with misspelled words. Remember, in coding, attention to detail is everything.

I'd start with rebuilding your dictionary to something like:

dictionary = {
    "transport": 'Transport', 'Transportation'
    "buildings":  'Housing', 'Provision of Housing'
    "energy": "Energy", "Energy; Housing; Income or financial inclusion"
    "food": "Food catering or production incl. farming"
}

Word of advice, learn the basics before diving into more complicated issues.

Dharman
  • 30,962
  • 25
  • 85
  • 135
NUSav77
  • 62
  • 6