在 for 循环语句中返回字典列表

时间:2020-12-19 10:59:06

标签: python pandas

所以,我有这个数据框

enter image description here

我需要将该分类列替换为序数/数字

所以,如果你一个一个地处理它,它看起来像:

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}}

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

考虑df

In [1543]: df
Out[1543]: 
  job_level person_level Employee_type
0      JG05         PG06     RM_type_A
1      JG04         PG04     RM_type_A
2      JG04         PG05     RM_type_B
3      JG03         PG03     RM_type_C

collections.CounterDictionary Comprehension 一起使用:

In [1539]: from collections import Counter

In [1537]: x = df.to_dict('list')

In [1544]: res = {k: Counter(v) for k,v in x.items()}

In [1545]: res
Out[1545]: 
{'job_level': Counter({'JG05': 1, 'JG04': 2, 'JG03': 1}),
 'person_level': Counter({'PG06': 1, 'PG04': 1, 'PG05': 1, 'PG03': 1}),
 'Employee_type': Counter({'RM_type_A': 2, 'RM_type_B': 1, 'RM_type_C': 1})}

Counter 本身返回一个 dict

答案 1 :(得分:0)

试试这个,不确定

replace_map_comp_list.append(replace_map_comp['job_level'][column])