【发布时间】: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