使用 for 循环有没有办法控制哪个 # 循环将值附加到列表中?

Posted

技术标签:

【中文标题】使用 for 循环有没有办法控制哪个 # 循环将值附加到列表中?【英文标题】:Using a for loop is there a way to control which # loop appends values to a list? 【发布时间】:2020-08-23 12:25:54 【问题描述】:

我目前正在使用 3 个名为 doctoratehigh_schoolbachelor 的数据框,它们看起来有点像这样:

    ID  age education   marital_status  occupation  annual_income   Age_25  Age_30  Age_35  Age_40  Age_45  Age_50
1   2   50  doctorate   married professional    mid 25 and over 30 and over 35 and over 40 and over 45 and over 50 and over
7   8   40  doctorate   married professional    high    25 and over 30 and over 35 and over 40 and over under 45    under 50
11  12  45  doctorate   married professional    mid 25 and over 30 and over 35 and over 40 and over 45 and over under 50
16  17  44  doctorate   divorced    transport   mid 25 and over 30 and over 35 and over 40 and over under 45    under 50

我正在尝试使用以下 for 循环根据 annual_income 列创建概率:

income_levels = ['low','mid','high']
education_levels = [bachelor,doctorate,high_school]

for inc_level in income_levels:
    for ed_level in education_levels:
        print(inc_level,len(ed_level[ed_level['annual_income'] == inc_level]) / len(ed_level))

它会产生这个,这就是我想要的:

low 0.125
low 0.0
low 0.25
mid 0.625
mid 0.75
mid 0.5
high 0.25
high 0.25
high 0.25

但是,我希望能够根据收入类别将这些值附加到列表中,列表将是 low_income,mid_income,high_income。我确信有一种方法可以修改我的 for 循环以便能够做到这一点,但我无法弥合到达那里的差距。谁能帮帮我?

【问题讨论】:

似乎将 3 个数据帧组合起来,然后使用 this answer 中的 groupby,这样您的标签和订单将被保留,您可以使用 tolist 或 todict 【参考方案1】:

在这种情况下,您尝试通过键/字符串查找列表。为什么不只使用列表的字典?

income_levels = ['low','mid','high']
education_levels = [bachelor,doctorate,high_school]

# initial dictionary
inc_level_rates = il: list() for il in income_levels

for inc_level in income_levels:
    for ed_level in education_levels:
        rate = len(ed_level[ed_level['annual_income'] == inc_level]) / len(ed_level)
        inc_level_rates[inc_level].append(rate)
        print(inc_level, rate)

print(inc_level_rates)

【讨论】:

以上是关于使用 for 循环有没有办法控制哪个 # 循环将值附加到列表中?的主要内容,如果未能解决你的问题,请参考以下文章

while until for switch 哪个不是shell的循环控制结构

增强的 for 循环不适用于将值分配给数组(Java)[重复]

在JavaScript循环语句中,for 和for.in 循环哪个效率更高

for循环执行顺序中外面的花括号和表达式3哪个先执行

使用单个昏暗数组将值分配给两个昏暗数组

有没有办法在 Python (3) for 循环中执行条件?