I am trying to use Pandas map to assign values to keys, where the keys would be strings returned if an entry in the DataFrame starts with a certain character.
Using an example from the Pandas docs, with the following DataFrame and my code:
import numpy as np
import pandas as pd
s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])
s.map({ lambda x: x if x.startswith('c') else None: 'kitten',
lambda x: x if x.startswith('d') else None: 'puppy',
lambda x: x if x.startswith('r') else None: 'bunny',
})
Expected result:
0 kitten
1 puppy
2 NaN
3 bunny
dtype: object
Currently, my code returns 4 NaN values. I am specifying startswith because I am not always able to know the last characters of the string in my DataFrame, but I know the first character/s. Any help would be appreciated.