I had always thought that .map
and .replace
were essentially the same, except you would use .replace
when you want to pass the values for keys not in the provided dictionary. However, I'm confused as to why .replace
throws a TypeError
when passed a dictionary with tuples as the key, while .map
works as expected with the same dictionary.
For example:
import pandas as pd
df = pd.DataFrame({'ID1': [1, 2, 3, 4, 5],
'ID2': ['A', 'B', 'C', 'D', 'E']})
df['tup_col'] = pd.Series(list(zip(df.ID1, df.ID2)))
dct = {(1, 'A'): 'apple', (3, 'C'): 'banana', (5, 'X'): 'orange'}
df.tup_col.map(dct)
#0 apple
#1 NaN
#2 banana
#3 NaN
#4 NaN
#Name: tup_col, dtype: object
df.tup_col.replace(dct)
TypeError: Cannot compare types 'ndarray(dtype=object)' and 'tuple'
So can I not use replace
in the case of a dictionary with tuples as the keys?