Python Numpy-遍历数组?

时间:2019-03-01 00:10:16

标签: python arrays numpy

这是DataQuest的练习。

我想我正在尝试遍历一个数组,但是它不允许我这样做。数组与列表有何不同?

样本量为32561,男性50%,女性50%为16280.50。

import numpy as np
import matplotlib.pyplot as plt

chi_squared_values = []

for i in range(1000):
    random_n = np.random.random((32561,))
    for array in random_n:
        male_count = 0
        female_count = 0
        for n in array: # Error on this line
            if n < 0.5:
                male_count =+ 1
            else:
                female_count =+ 1
        male_diff = (male_count - 16280.5) ** 2 / 16280.5
        female_diff = (female_count - 16280.5) ** 2 / 16280.5
        chi_squared_value = male_diff + female_diff
        chi_squared_values.append(chi_squared_value)

plt.hist(chi_squared_values)
plt.show()

# Output: TypeError: 'numpy.float64' object is not iterable

正确的参考答案是:

chi_squared_values = []
from numpy.random import random
import matplotlib.pyplot as plt

for i in range(1000):
    sequence = random((32561,))
    sequence[sequence < .5] = 0
    sequence[sequence >= .5] = 1
    male_count = len(sequence[sequence == 0])
    female_count = len(sequence[sequence == 1])
    male_diff = (male_count - 16280.5) ** 2 / 16280.5
    female_diff = (female_count - 16280.5) ** 2 / 16280.5
    chi_squared = male_diff + female_diff
    chi_squared_values.append(chi_squared)

plt.hist(chi_squared_values)

1 个答案:

答案 0 :(得分:1)

减少数量,以便您查看发生的情况:

for i in range(1):
    random_n = np.random.random((5,))
    for array in random_n:
        print("array", array)

输出:

array 0.134163286857
array 0.872361053661
array 0.794873889688
array 0.68134812363
array 0.726452821311

random_n只是一个浮点数数组。因此,您命名为array的是单个浮点数。您无法对此进行迭代。

通过更改解决方案的结构试图实现什么?您的内循环应该做什么?