-2

Is there a way to map characters for a column in Pandas.

For example, I would like to map a column say info like this {"1": "US", "2":"DE", "3":"CA", "4":"AU", "5":"BE"}

So instead of the numbers, I would like something US and the rest to show

EDIT NOTE: I dont want to explode the column, I want to keep them as they are, only replacing numbers with strings

0   ['3']
1   ['6']
2   ['3','4']
3   ['3','4','6']
4   ['3','4']
5   ['6']
6   ['6']
7   ['5']
8   ['5']
9   ['3', '4', '1']
JA-pythonista
  • 1,225
  • 1
  • 21
  • 44

2 Answers2

2

Looks like you could do:

d = {"1": "US", "2":"DE", "3":"CA", "4":"AU", "5":"BE"}
df.dropna().explode('my_col').my_col.map(d).groupby(level=0).agg(list).reindex(df.index)
yatu
  • 86,083
  • 12
  • 84
  • 139
1

If you don't wanna explode, use apply. But remember the explode method may be way faster than this on large dataframes

Test Dataframe

>>> df
        test
0     [3, 4]
1        [6]
2        [3]
3  [3, 4, 6]

Mapping dictionary

>>> info =  {"1": "US", "2":"DE", "3":"CA", "4":"AU", "5":"BE"}

CODE

>>> df.test.apply(lambda x: [info.get(str(i)) for i in x])
0          [CA, AU]
1            [None]
2              [CA]
3    [CA, AU, None]
Name: test, dtype: object
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55