Convert a list of labels into number given a defined dictionary

Viewed 26

I have the following dictionary defined in my code: label_dict = {'positive': 1, 'negative': 0}

I also have a label_list that contains two possible values: "positive" and "negative".

I want to essentially map each label in label_list to the respective numeric value defined by label_dict.

I have the following for loop defined as well: for label in range(len(label_list)): for iterating through label_list.

How can I accomplish this? Any help is much appreciated.

1 Answers

One solution is to convert your label_list to Series and use mapping and then return it back to list again like that:

import pandas as pd

label_dict = {'positive': 1, 'negative': 0}
label_list = ["positive","negative","negative","positive",
               "negative","positive","negative"]
new_lst = pd.Series(label_list).map(label_dict).tolist() 

#output
print(new_lst)    # [1, 0, 0, 1, 0, 1, 0]
Related