0

I have a dictionary called mapped

{'A=': 0,
  'B=': 1,
  'C=': 2,
  'D=': 3}

and a series called subject

0       [A=4.2, B=402, C=100]
1       [A=4.2, B=399, C=200]
2       [A=FIX.4.2, B=398, C=150]

I want the string instances in my series to be replaced by the value of dictionary in following way

0       [0=4.2, 1=402, 2=100]
1       [0=4.2, 1=399, 2=200]
2       [0=FIX.4.2, 1=398, 2=150]

I tried

subject=subject.replace(mapped_1, regex=True)
df=subject.apply(lambda x : x,mapped)

but I cannot replace inside the strings and python only changes the first instance.

1
  • could you include the DataFrame and Series constructors for your data posted here? Commented Jan 24, 2022 at 20:00

1 Answer 1

1

I'd suggest a method that replace all keys by all values, then apply it

def replacer(value, mappings):
    for k, v in mappings.items():
        value = value.replace(k, v)
    return value



mapped = {'A=': 0, 'B=': 1, 'C=': 2, 'D=': 3}
subject = pd.Series(["[A=4.2, B=402, C=100]", "[A=4.2, B=399, C=200]", "[A=FIX.4.2, B=398, C=150]"])
mapped_ok = {k.replace("=", ""): str(v) for k, v in mapped.items()}
subject = subject.apply(lambda x: replacer(x, mapped_ok))
print(subject)

0        [0=4.2, 1=402, 2=100]
1        [0=4.2, 1=399, 2=200]
2    [0=FIX.4.2, 1=398, 2=150]
dtype: object

Or with functools.reduce

from functools import reduce

def replacer(value, mappings):
    return reduce(lambda val, kv: val.replace(kv[0], kv[1]),
                  mappings.items(),
                  value)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.