简体   繁体   English

如何在Numpy中方便地将range(10)分配给形状为(10,1)的ndarray?

[英]How to assign range(10) to a ndarray which shape is (10, 1) conveniently in Numpy?

I tried this: 我尝试了这个:

import numpy as np
a = np.empty((1, 10, 1), np.int8)
a[0] = range(10)

It throw error: ValueError: could not broadcast input array from shape (10) into shape (10,1) 它引发错误: ValueError: could not broadcast input array from shape (10) into shape (10,1)

您可以执行a[0, :, 0] = range(10)

Several options that work in this case: 在这种情况下可以使用的几个选项:

a[0, :, 0] = np.arange(10)  # assign to 1D slice

a[0].flat = range(10)  # assign to flattened 2D slice

a[0] = np.arange(10).reshape(10, 1)  # bring the rigth side into correct shape

a[0] = np.arange(10)[:, np.newaxis]  # bring the rigth side into correct shape

Note the use of np.arange instead of range . 注意使用np.arange代替range The former directly creates an ndarray with a sequence of values, while the latter creates an iterable that needs to be converted into an array for the assignment. 前者直接创建具有值序列的ndarray,而后者创建需要迭代的可迭代对象,以进行赋值。

In the case of assigning to flat it makes sense to use range because both are iterators. 在分配flat时,使用range是有意义的,因为两者都是迭代器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从10个不同的(104,)维numpy.ndarray创建一个(104,1,10)维numpy.ndarray - creating a (104,1,10) dimensional numpy.ndarray from 10 different (104,) dimensional numpy.ndarray Numpy: 如何 map f: (shape (3) ndarray) --> (float) over an ndarray of shape (...,3) 以获得 ndarray of shape (...)? - Numpy: How to map f: (shape (3) ndarray) --> (float) over an ndarray of shape (…,3) to get ndarray of shape (…)? IndexError:访问numpy ndarray形状时元组索引超出范围 - IndexError: tuple index out of range while accessing numpy ndarray shape Numpy ndarray形状有3个参数 - Numpy ndarray shape with 3 parameters 如何在 Python 列表列表中查找重复项,哪些元素是 numpy.ndarray 的形状(9、103) - How to find duplicates in a Python list of lists which elements are numpy.ndarray of shape (9, 103) 如何用pybind11绑定一个以numpy.array()作为参数(例如,形状为(10,10,3))的函数? - How with pybind11 to bind a function that takes as argument a numpy.array() with, for instance, a shape (10, 10, 3)? 将numpy ndarray分配给列表 - Assign numpy ndarray to list 给定字节缓冲区、数据类型、形状和步幅,如何创建 Numpy ndarray - Given a byte buffer, dtype, shape and strides, how to create Numpy ndarray 如何使用插值将任意 Numpy NDArray 调整为新形状 - How to resize an arbitrary Numpy NDArray to a new shape with interpolation numpy-如何方便地比较自定义dtype? - numpy - How to compare custom dtypes conveniently?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM