簡體   English   中英

Numpy:從一維整數數組創建新數組,其中整數數組中的每個元素表示新數組中的元素數

[英]Numpy: Create new array from 1d integer array where each element in integer array represents the number of elements in the new array

這看起來應該很簡單,但我很難過(對 numpy 來說也很新。)

我有一個一維整數數組a

我想生成一個新的一維數組b使得:

  • b中的元素的數量等於所述元素的總和
  • B中的值等於由相應的元件分開的一些任意的常數。

這是一口,所以這里有一個我想讓它更具體的例子:

a = array([2,3,3,4])
CONSTANT = 120
.
.
.
b = array([60,60,
           40,40,40,
           40,40,40,
           30,30,30,30])

任何幫助表示贊賞!

我認為一個非常明確的方法是

import numpy as np
a = np.array([2,3,3,4]) 
constant = 120

#numpy.repeat(x,t) repeats the val x t times you can use x and t as vectors of same len
b = np.repeat(constant/a , a)

你可以用np.concatenate和老式的zip來做到這一點:

>>> elements = CONSTANT / a
>>> np.concatenate([np.array([e]*n) for e, n in zip(elements, a)])
array([60., 60., 40., 40., 40., 40., 40., 40., 30., 30., 30., 30.])

暫無
暫無

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

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