Используя a для l oop, есть ли способ контролировать, какой # l oop добавляет значения в список? - PullRequest
1 голос
/ 08 мая 2020

Я сейчас работаю с 3 фреймами данных с именами doctorate, high_school и bachelor, которые выглядят примерно так:

    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

Я пытаюсь создать вероятности на основе annual_income столбец, используя следующее для l oop:

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 l oop, чтобы это было возможно, но я не могу восполнить пробел, чтобы добраться туда. Может ли кто-нибудь мне помочь?

1 Ответ

0 голосов
/ 08 мая 2020

В этом случае вы пытаетесь найти список с помощью ключа / строки. Почему бы просто не использовать список списков?

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)
...