所以,我有这个数据帧
我需要将分类列替换为序号/数字
所以,如果你一个接一个地处理它,它会像:
labels = df_main_correlation['job_level'].astype('category').cat.categories.tolist()
replace_map_comp = {'job_level' : {k: v for k,v in zip(labels,list(range(1,len(labels)+1)))}}
print(replace_map_comp)
它会回来的
{'job_level': {'JG03': 1, 'JG04': 2, 'JG05': 3, 'JG06': 4}}
但是您可以使用for循环来处理所有列,对吗
我试过这个
columns_categorical =list(df_main_correlation.select_dtypes(['object']).columns) #take the columns I want to process
replace_map_comp_list = []
for i, column in enumerate(columns_categorical):
labels = df_main_correlation[column].astype('category').cat.categories.tolist()
replace_map_comp = {column : {k: v for k,v in zip(labels,list(range(1,len(labels)+1)))}} # Return dictionary
print(replace_map_comp)
replace_map_comp_list.append(replace_map_comp[i])
replace_map_comp_list
但它只会回来
{'job_level': {'JG03': 1, 'JG04': 2, 'JG05': 3, 'JG06': 4}}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-202-acc2ad8defaa> in <module>()
8 #df_main_correlation.replace(replace_map_comp, inplace=True)
9
---> 10 replace_map_comp_list.append(replace_map_comp[i])
11 replace_map_comp_list
KeyError: 0
我的预期结果是
{'job_level': {'JG03': 1, 'JG04': 2, 'JG05': 3, 'JG06': 4}}
{'person_level': {'PG01': 1, 'PG02': 2, 'PG03': 3, 'PG04': 4, 'PG05': 5, 'PG06': 6, 'PG07': 7, 'PG08': 8}}
{'Employee_type': {'RM_type_A': 1, 'RM_type_B': 2, 'RM_type_C': 3}}
有什么建议吗
考虑^ {CD1>}:
将^{} 与^{} 一起使用:
Counter
本身返回一个dict
试试这个,不确定
相关问题 更多 >
编程相关推荐