0

I have an excel file which has a column as such:

Numbers (Column Name)

1 10 11

1 10 13

1 10 12

1 15 23

Each Number in every row denotes a letter where 1 = 'a', 2 = 'b'... and so on.

How do I map each number of each row to a letter?

Thank you

dataframe.meal_swap.replace(mappings)

line Value

0 NaN

1 NaN

2 NaN

3 NaN

4 NaN

     ...  

3200 1 6 20

3201 1 6 21

3202 1 6 21

3203 1 6 21

3204 1 6 21

Name: meal_swap, Length: 3205, dtype: object

1 Answers1

2

Create a dictionary of all the mappings

mappings = {1: 'a', 10: 'b', 15: 'c', 11: 'd', 12: 'e', 13: 'f', 23: 'g'}

Use pandas.DataFrame.replace

df.replace(mappings)

Or, Use pandas.DataFrame.applymap to apply the map (Less efficient)

df.applymap(lambda x: mappings.get(x, pd.np.nan))
anky
  • 74,114
  • 11
  • 41
  • 70
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
  • 1
    Yeah! Guess I missed that. It would simplify a lot and it's more efficient. Thanks for the help @anky – Vishnudev Krishnadas Mar 13 '21 at 15:15
  • dataframe['meal_swap'].replace(mappings) 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN ... 3200 1 6 20 3201 1 6 21 3202 1 6 21 3203 1 6 21 3204 1 6 21 Name: meal_swap, Length: 3205, dtype: object I just ran it, but it still shows the same output... am I doing it right? – Aqeel Ahlam Mar 13 '21 at 16:21
  • Please improve your question by providing proper example. You might wanna refer https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples for clarification. @AqeelAhlam – Vishnudev Krishnadas Mar 13 '21 at 16:25