使用嵌套循环

时间:2016-03-27 19:09:41

标签: python arrays numpy

我不熟悉编码并尝试编写一个程序来计算A / B测试中的样本大小n

我陷入了下面主要功能的嵌套循环中。我想创建一个数组n_dist_all,其中3个不同的行包含n的值,具体取决于使用嵌套循环的不同beta值。但是,该函数只是在同一行中添加三个不同beta的值。我正在尝试使用numpy.hstack。我也试过了concatenateappend,但他们都给了我相同的结果。

import numpy as np
import math
import scipy.stats as st

def N(alpha, beta, delta):
    Z_alpha = st.norm.ppf(1-alpha)
    Z_beta = st.norm.ppf(1-alpha)
    pA = 0.01
    pB = pA + delta
    qA = 1.0 - pA
    qB = 1.0 - qA

    n = (((Z_alpha*math.sqrt((pA+pB)*(qA+qB)/float(2)))+(Z_beta*math.sqrt((pA*qA)*(pB*qB))))/(pA-pB))**float(2)
    return int(n)


def float_range(start, stop, step):
    i = start
    while i < (stop + step):
        yield i
        i += step


def main():
    n_dist_all = np.array([])

    beta_1 = 0.2
    beta_2 = 0.1
    beta_3 = 0.05
    beta_group = [beta_1, beta_2, beta_3]

    alpha = 0.05

    for beta in beta_group:
        n_dist = np.array([])
        for delta in float_range(0.001,0.03,0.0005):
            n_dist = np.append(n_dist, N(alpha, beta, delta))
        n_dist_all = np.hstack((n_dist_all, n_dist))
        n_dist = []
    print n_dist_all

if __name__ == "__main__":
        main()

1 个答案:

答案 0 :(得分:0)

从你的python程序改变hstack()到vstack()。示例如下。

a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.array([7,8,9])
np.vstack((a,b,c)) # This give the following array

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])