【问题标题】:Assign values to an array of indexes in Python在 Python 中为索引数组赋值
【发布时间】:2021-11-08 19:11:21
【问题描述】:

我有一个大小为 300x5 的数组。在此,如果某个索引和索引 4 的列包含相应的值,则索引为 3 的列包含。

我创建了一个新数组,我试图在这个新数组的索引 3 位置分配索引 4 中的值。我试过了,但它会引发错误。

new_arr[old_arr[:,3]] = old_arr[:,4]

与我想做的事相关的例子之一

new_arr = np.ones((200,1))
new_arr[[2,3,4]] = [22,44,11]

会报错

ValueError: shape mismatch: value array of shape (3,)  could not be broadcast to indexing result of shape (3,1)

【问题讨论】:

    标签: arrays python-3.x indexing


    【解决方案1】:

    使用此代码:new_arr[old_arr[:,3]],您尝试访问来自old_arr[:,3] 中的值的索引new_arr,然后您得到IndexError

    这对你有帮助吗?

    new_arr = np.zeros((300, 5))
    new_arr[:,3] = old_arr[:,4]
    

    对于已编辑的问题,您需要reshape

    new_arr = np.ones((200,1))
    new_arr[[2,3,4]] = np.array([2,4,6]).reshape(3,1)
    # OR
    # new_arr[2:5] = np.array([22,44,11]).reshape(3,1)
    

    【讨论】:

    • 这不起作用,因为old_arr[:,3]中的索引不按顺序排列
    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    相关资源
    最近更新 更多