2

I have something like the following dataframe:

import pandas as pd
import numpy as np

df = pd.DataFrame()
df['ID1'] = [0, 1, 4, 6, 7]
df['ID2'] = [6, 2, 3, 4, np.nan]
df['ID3'] = [np.nan, np.nan, 7, np.nan, np.nan]
>>> df
   ID1  ID2  ID3
0    0    6  NaN
1    1    2  NaN
2    4    3    7
3    6    4  NaN
4    7  NaN  NaN

And the following set of keys:

keys = pd.Series(['Orange', 'Blue', 'Purple', 'Red', 'Green', 'Pink', 'Brown', 'Black'],
                 name='ID')
>>> keys
0    Orange
1      Blue
2    Purple
3       Red
4     Green
5      Pink
6     Brown
7     Black
Name: ID, dtype: object

I want to replace each element in the dataframe with it's appropriate key. I can do this column by column using the 'map function':

>>> df['ID1'].map(keys)
0    Orange
1      Blue
2     Green
3     Brown
4     Black
Name: ID1, dtype: object

However, how can I do this to my entire dataframe at once? I would think that this is where 'applymap' would come in, but I seem to be using it incorrectly as I get an error message when I try df.applymap(keys).

Any suggestions on how I can do this?

1 Answer 1

1

This is a good use case of a lambda function with apply where you map each column in the dataframe.

>>> df.apply(lambda col: col.map(keys))
      ID1     ID2    ID3
0  Orange   Brown    NaN
1    Blue  Purple    NaN
2   Green     Red  Black
3   Brown   Green    NaN
4   Black     NaN    NaN
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.