将标签列表转换为给定字典的数字

原文标题Convert a list of labels into number given a defined dictionary

我的代码中定义了以下字典:label_dict = {'positive': 1, 'negative': 0}

我还有一个 label_list 包含两个可能的值:“正”和“负”。

我想基本上将 label_list 中的每个标签映射到 label_dict 定义的相应数值。

我还定义了以下 for 循环:for label in range(len(label_list)):用于遍历 label_list。

我怎样才能做到这一点?任何帮助深表感谢。

原文链接:https://stackoverflow.com//questions/71905457/convert-a-list-of-labels-into-number-given-a-defined-dictionary

回复

我来回复
  • Phoenix的头像
    Phoenix 评论

    一种解决方案是将您的label_list转换为Series并使用映射,然后将其再次返回到列表中,如下所示:

    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]
    
    2年前 0条评论