簡體   English   中英

如何在Numpy中方便地將range(10)分配給形狀為(10,1)的ndarray?

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

我嘗試了這個:

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

它引發錯誤: ValueError: could not broadcast input array from shape (10) into shape (10,1)

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

在這種情況下可以使用的幾個選項:

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

注意使用np.arange代替range 前者直接創建具有值序列的ndarray,而后者創建需要迭代的可迭代對象,以進行賦值。

在分配flat時,使用range是有意義的,因為兩者都是迭代器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM