在NumPy数组中计算不同列的值

3

我有一个二维数组,其中第一列填充了一些值,其他列为零。我希望能够使用numpy实现与MS Excel相同的操作,即根据第一列进行计算,并将计算结果填充到其他列中。以下是一个最小化工作示例:

import numpy as np

a = np.zeros(20, dtype=np.int8).reshape(4,5)

b = [1, 2, 3, 4]

b = np.array(b)

a[:, 0] = b

# don't change the first column
for column in a[:, 1:]:
    a[:, column] = column[0]+1

预期输出:
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8]], dtype=int8)

生成的输出内容:
array([[1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0]], dtype=int8)

任何帮助将不胜感激。


打印迭代中的column1的值。它是列的值还是索引? - hpaulj
2个回答

3
循环速度较慢,生成所需的数组无需循环即可完成:
>>> a = np.ones(20, dtype=np.int8).reshape(4,5)
>>> a[:, 0] = b
>>> a
array([[1, 1, 1, 1, 1],
       [2, 1, 1, 1, 1],
       [3, 1, 1, 1, 1],
       [4, 1, 1, 1, 1]], dtype=int8)
>>> np.cumsum(a, axis=1)
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8]])

出了什么问题

让我们从这个数组开始,就像问题描述中一样:

>>> a
array([[1, 0, 0, 0, 0],
       [2, 0, 0, 0, 0],
       [3, 0, 0, 0, 0],
       [4, 0, 0, 0, 0]], dtype=int8)

现在,使用问题中的代码,让我们循环并看看column实际上是什么:

>>> for column in a[:, 1:]:
...   print(column)
... 
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]

如您所见,column并不是列的索引,而是列中的实际值。因此,以下代码并不能达到您期望的效果:

a[:, column] = column[0]+1

另一种方法

如果我们想要循环(以便我们可以做更复杂的事情),这里是生成所需数组的另一种方法:

>>> b = np.array([1, 2, 3, 4])
>>> np.column_stack([b+i for i in range(5)])
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8]])

虽然开始不错,但是如果a是零的话,np.cumsum方法就不起作用了。 - Mazdak
@Kasramvd 不错的评论,但请注意,这就是为什么我在使用cumsum时创建了一个包含1的a - John1024
@John1024 谢谢你的解释。但是如果我想进行更复杂的计算,而不仅仅是求和1呢? - Maxwell's Daemon
也许这不是楼主想要的。此外,解决这个问题也很有趣 :). - Mazdak
@david_doji 我刚刚在答案中添加了另一种方法,可以扩展以执行比求和更复杂的操作。 - John1024
@John1024 再次感谢!这正是我在寻找的东西! - Maxwell's Daemon

1
您对column的使用有点模糊:在for column in a[:, 1:]中,它被视为列,在循环体中,它被视为列的索引。您可以尝试使用以下代码代替:

for column in range(1, a.shape[1]):
    a[:, column] = a[:, column-1]+1

a
#array([[1, 2, 3, 4, 5],
#       [2, 3, 4, 5, 6],
#       [3, 4, 5, 6, 7],
#       [4, 5, 6, 7, 8]], dtype=int8)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接