gpt4 book ai didi

python - 使用数组作为列填充预定义的 numpy 数组

转载 作者:太空宇宙 更新时间:2023-11-03 18:57:28 27 4
gpt4 key购买 nike

通过阅读 Python 文档和 stackoverflow,我无法弄清楚一些事情。可能我的想法是错误的..

假设我有一个预定义的 2D Numpy 数组,如下所示:

a = np.zeros(shape=(3,2)) 
print a
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])

现在我想用一维数据数组(逐一)填充此二维数组的每一列,如下所示:

b = np.array([1,2,3])

# Some code, that I just can't figure out. I've studied insert, column_stack,
# h_stack, append. Nothing seems to do what I need

print a
array([[ 1., 0.],
[ 2., 0.],
[ 3., 0.]])

c = np.array([4,5,6])

# Some code, that I just can't figure out. I've studied insert, column_stack,
# h_stack, append. Nothing seems to do what I need

print a
array([[ 1., 4.],
[ 2., 5.],
[ 3., 6.]])

如有任何建议,我们将不胜感激!

最佳答案

您可以通过切片分配给列:

>>> a[:,0] = b
>>> a
array([[ 1., 0.],
[ 2., 0.],
[ 3., 0.]])

要一次性分配它们而不是一次分配一个,请使用np.column_stack:

>>> np.column_stack((b, c))
array([[1, 4],
[2, 5],
[3, 6]])

如果您需要将其放回到同一个数组中,而不仅仅是具有相同的名称,您可以分配给包含整个矩阵的切片(与列表一样):

>>> a[:] = np.column_stack((b, c))
>>> a
array([[ 1., 4.],
[ 2., 5.],
[ 3., 6.]])

关于python - 使用数组作为列填充预定义的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16960068/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com