在矩阵中创建Running Total列?

时间:2017-11-10 14:06:20

标签: python python-2.7 numpy

this question I recently posted & resolved相关。

如果要将矩阵的第3列更改为总和的总计,我将如何调整我的代码? 这是我到目前为止所处的位置:

def dice(n):
    rolls = np.empty(shape=(n, 3),dtype=int)
    for i in range(n):
        x = random.randint(1,6)
        y = random.randint(1,6)
        if x in [1,3,5] or y in [1,3,5]:      
            sum_2_dice = x + y 
            z = np.cumsum(sum_2_dice)
            rolls[i,:] = x, y, z
        else:
            sum_2_dice = -(x+y)  # meaning you "lose the sum" basically
            z = np.cumsum(sum_2_dice)
            rolls[i,:] = x, y, z
    return rolls `

例如:dice(2)

返回

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

什么时候真的要回来了:

array[[2, 6, -8],
      [1, 3, -4],
      [5, 2,  3])

我认为np.cumsum会做点什么,但我不确定。是否需要使用while循环(我不确定它应用于何处)?我尝试了各种调整,而不是z = np.cumsum(sum_2_dice)我做sum_2_dice += sum_2_dice(因此跟随它的代码是rolls[i,:] = x, y, sum_2_dice,但这是非常错误的,因为所有最终做的都是加倍每列中的总和值,不进行任何类型的运行总计算。

1 个答案:

答案 0 :(得分:0)

为了您的目的,跟踪z的一种简单方法是在循环外部初始化它,然后继续添加sum_2_dice的值。

def dice(n):
    z = 0
    rolls = np.empty(shape=(n, 3),dtype=int)
    for i in range(n):
        x = random.randint(1,6)
        y = random.randint(1,6)
        if x in [1,3,5] or y in [1,3,5]:
            sum_2_dice = x + y
            z += sum_2_dice
            rolls[i,:] = x, y, z
        else:
            sum_2_dice = -(x+y)  # meaning you "lose the sum" basically
            z += sum_2_dice
            rolls[i,:] = x, y, z
    return rolls


print (dice(3))
#[[ 6  2 -8]
# [ 4  5  1]
# [ 1  5  7]]

作为参考,numpy.cumsum通常用于获取数组元素的累积总和,例如:

test = np.arange(0,5,1)
print (test)
# [0 1 2 3 4]

print (np.cumsum(test))
# [0 1 3 6 10]
相关问题