【问题标题】:Renaming dictionary keys through a loop problem通过循环问题重命名字典键
【发布时间】:2021-04-22 19:40:01
【问题描述】:

我的数据框 df 中有一个列“EDU”。我试图用 value_counts()、poe_dict 创建一个字典。看起来像这样。

edu_m=df['EDU'].sort_values()
poe_dict = edu_m.value_counts(normalize=True).to_dict()
poe_dict

{4: 0.47974705779026877,
 3: 0.24588090637625154,
 2: 0.172352011241876,
 1: 0.10202002459160373}

现在,我正在尝试用我放入列表中的这些字符串替换键“4,3,2,1”。

n_keys=["college","高中以上但不上大学","高中","高中以下"]

如果我单独做每一个,这运行正常,给我预期的结果。

In:
   poe_dict['college'] = poe_dict.pop(4)
   poe_dict['more than high school but not college'] = poe_dict.pop(3)
   poe_dict['high school'] = poe_dict.pop(2)
   poe_dict['less than high school'] = poe_dict.pop(1)

Out:
{'college': 0.47974705779026877,
'more than high school but not college': 0.24588090637625154,
'high school': 0.172352011241876,
'less than high school': 0.10202002459160373}

但是,如果我尝试将其作为一个循环来执行,它会产生这个。

In:
for key, n_key in zip(poe_dict.keys(), n_keys):
   poe_dict[n_key] = poe_dict.pop(key)
poe_dict

Out:
{2: 0.172352011241876,
1: 0.10202002459160373,
'high school': 0.47974705779026877,
'less than high school': 0.24588090637625154}

所以我不明白为什么循环不适用于键 2 和 1?

我也尝试过调试它,看看在这样的循环中会发生什么。

In:
for key, n_key in zip(poe_dict.keys(), n_keys):
  
   print (key,n_key)
   poe_dict[n_key] = poe_dict.pop(key)
   
Out:
4 college
3 more than high school but not college
college high school
more than high school but not college less than high school

【问题讨论】:

    标签: python-3.x pandas loops dictionary


    【解决方案1】:

    你在 for 循环中遍历 poe_dict 的键。然而,当语句为poe_dict[n_key] = poe_dict.pop(key) 已运行时, poe_dict 的键被修改。因此,密钥信息出错。正确的方法是将 peo_dict 的键存储到一个列表list(poe_dict.keys()) 中,然后循环遍历这个新的键列表。

    poe_dict = {4: 0.47, 3:0.25, 2:0.17, 1:0.10}
    
    n_keys = ['college', 'more than high school but not college','high school', 'less than high school' ]
    keylist = list(poe_dict.keys())
    for key, n_key in zip(keylist, n_keys):
       print (key,n_key)
       poe_dict[n_key] = poe_dict.pop(key)
    print (poe_dict)
    

    结果会是

    {'college': 0.47, 'more than high school but not college': 0.25, 'high school': 0.17, 'less than high school': 0.1}
    

    【讨论】:

    • 谢谢您,先生。我没有意识到它们都应该是列表。
    猜你喜欢
    • 2012-05-29
    • 2013-05-04
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2015-12-29
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多