Python中字典的巧用!

版权声明:未经博主允许不得转载。 https://blog.csdn.net/qq_43774897/article/details/88869515

问题描述

假设你现在有一列名为score的数据,里面数据包含’Excellent’, ‘Good’, ‘Ok’, ‘Not_Ok’, 'Bad’这5个类型,你想把他们换成1,2,3,4,5来对应标注。

问题解决

首先生成示例数据

import pandas as pd

score = ['Excellent','Good','Ok','Not_Ok','Bad','Excellent','Good','Good',\
         'Excellent','Not_Ok','Excellent',\
         'Good','Good','Not_Ok','Not_Ok']
         
scores = pd.DataFrame({'score':score})

在这里插入图片描述

targets = scores['score'].unique()     #查看唯一类型的值

在这里插入图片描述

data_dict = {}
count = 1
for data in targets:
    data_dict[data] = count      #  将类别变量和数值设置成键值对
    count += 1
    
 print(data_dict)

在这里插入图片描述

scores['score'] = scores['score'].replace(data_dict)
print(scores['score'])

在这里插入图片描述
这样,所有的变量都变成我们想要的赋值了!

猜你喜欢

转载自blog.csdn.net/qq_43774897/article/details/88869515