1

I have a dataframe with a column that includes a list of IDs. I've created a dictionary that associates the IDS with a string value. I'd like to replace the int values with the string.

Name       Label_ID  
Project1   [1]
Project2   [3,5]

label_map={1:'blue', 3:'green',5:'large'}

I want to get an output of:

Name       Label_ID  
Project1   [blue]
Project2   [green, large]

I've tried using:

test['Tags']=test['Label_ID'].map(label_map)

This code runs, but the resulting 'Tags' column is just NaNs. Any guidance would be appreciated.

1 Answer 1

1

IIUC, you can explode your df and then map the values then reapply an groupby along the index to get your values.

note your list may be a string so i've added the the literal eval method from the ast library.

the reason map won't work here is because your applying it a list, when you need to apply it series wise or element wise using apply.

from ast import literal_eval


df["Label_Map"] = (
    df["Label_ID"]
    .apply(literal_eval) # remove if not needed.
    .explode()
    .map(label_map)
    .groupby(level=0)
    .agg(list)
)

print(df)

       Name Label_ID       Label_Map
0  Project1      [1]          [blue]
1  Project2    [3,5]  [green, large]
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.