Home > Software design >  Replace string using MAP and LAMBDA in Python
Replace string using MAP and LAMBDA in Python

Time:10-07

I have a dataframe column called 'event' in a dataframe called 'calendar'. Obviously it contains event names and I want to replace those names by a single string. To do so, I use a few filters based on the content of the event names.

For instance, I want to replace all the names containing 'BoE','BoC','Fed', 'ECB' ,'RBA' or 'RBNZ' and also contain the word 'Speak' by simply 'Speak'.

To achieve that, I made this code:

banks=['BoE','BoC','Fed', 'ECB' ,'RBA','RBNZ']
calendar['event'] = list(map(lambda x : 'Speak' if any(bancs) and 'Speak' in x else x, calendar['event']))

Most of times it works fine, but I usally get the error: 'DataFrame' object is not callable'. I guess there's something wrong in the syntax so I'll be thankfull with any correction or any alternative code that can be useful

CodePudding user response:

Your current code seems to have both typos and logical errors (e.g. your use of any).
Try this -

banks=['BoE','BoC','Fed', 'ECB' ,'RBA','RBNZ']
calendar['event'] = list(map(lambda x : 'Speak' if (any([b in x for b in banks]) and 'Speak' in x) else x, calendar['event']))

Testing on a simple example:

calendar = pd.DataFrame(columns=['event'])
calendar['event'] = ['Speak BoC', 'BoE', 'Speak Q', 'RBNZSpeak']  # Only 1st and 3rd should be replaced by "Speak"
banks=['BoE','BoC','Fed', 'ECB' ,'RBA','RBNZ']
calendar['event'] = list(map(lambda x : 'Speak' if (any([b in x for b in banks]) and 'Speak' in x) else x, calendar['event']))
print(calendar.event)
# 0      Speak
# 1        BoE
# 2    Speak Q
# 3      Speak

But none of your typos/mistakes seem to relate to your error, so there might be problems elsewhere in your code.
You should post an error-producing example if the answers here don't address your problem.

  • Related