NotaCoder
NotaCoder

Reputation: 37

How do I replace keys in strings in a pandas data frame in a loop from dictionaries with values?

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.

Upvotes: 0

Views: 61

Answers (1)

azro
azro

Reputation: 54148

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)

Upvotes: 1

Related Questions