我在我的dataframe,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=“学院”,“比高中更多,但不是大学”,“高中”,“低于高中”
如果我每个人都这样做,运行正常,给我预期的结果。
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发布于 2021-01-18 14:19:41
在for循环中遍历poe_dict的键。但是,在运行poe_dict语句是poe_dict[n_key] = poe_dict.pop(key)时,会修改poe_dict[n_key] = poe_dict.pop(key)的键。因此,密钥信息会出错。正确的方法是将peo_dict的键存储到list 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}https://stackoverflow.com/questions/65775685
复制相似问题