Blue Week Special Offer | Brighten your week!
days
hours
minutes
seconds

Race Chi-squared

Hi! I dont understand the solution code. I understand the logic how to calculate chi-squared, but not sure I understand all the code.
Screen Link: https://app.dataquest.io/m/99/chi-squared-tests/9/increasing-degrees-of-freedom
What are the i,obs below? enumerate function is to count observed list, so i stands for each element of the list,but what about obs?
Thank you!

    exp = expected[i]```

My Code: <!--Enclose your code in 3 backticks to format properly-->

diffs =
observed = [27816, 3124, 1039, 311, 271]
expected = [26146.5, 3939.9, 944.3, 260.5, 1269.8]

for i, obs in enumerate(observed):
exp = expected[i]
diff = (obs - exp) ** 2 / exp
diffs.append(diff)

race_chisq = sum(diffs)

Hi @candiceliu93,

In this code, i is the index of an item at the current iteration through the observed list, obs - the value of that item. I’ll illustrate it with this example:

fruit_list = ['apple', 'kiwi', 'melon', 'grape', 'ananas']

for i, value in enumerate(fruit_list):
    print(i, value)

Output::

0 apple
1 kiwi
2 melon
3 grape
4 ananas
1 Like

Think about it this way, if the only purpose of enumerate was to generate counts, why not just for i in range(len(observed))?

1 Like

Posting my version here, which is slightly longer but maybe is easier to understand given the labels:

observed = {
    "White": 27816,
    "Black": 3124,
    "Asian": 1039,
    "Amer Indian": 311,
    "Other": 271   
}

expected = {
    "White": 26146.5,
    "Black": 3939.9,
    "Asian": 944.3,
    "Amer Indian": 260.5,
    "Other": 1269.8
}


chi_list = []

for i in observed:
    chi_total = (observed[i]-expected[i])**2/expected[i]
    chi_list.append(chi_total)
    
race_chisq = numpy.sum(chi_list)
1 Like