[英]How to create a 2D array in Python where each column has a different and random number of elements
我正在編寫到達探測器的光子的蒙特卡羅模擬。 檢測到的光子N_detected
遵循泊松分布(我使用scipy.stats.poisson
生成)並且每個光子的檢測時間遵循給定的概率分布 function (PDF)。 為了生成N_detected
光子的檢測時間,我使用numpy.random.random()
function 生成介於 0 和 1 之間的N_detected
隨機數,並使用Inverse Transform Method 。
我必須多次運行模擬。 因此,為了避免重復很多次,我想使用 numpy arrays 一次進行每個模擬。 作為最終結果,我想獲得一個由N_sim
列組成的二維數組,其中每一列對應於不同的模擬,並包含生成的檢測時間。 問題是每個模擬都會產生不同數量的光子(因為它是隨機的),而且我找不到創建具有不同長度列的 2D 陣列的方法。
我的一個想法是創建具有相同長度(最大N_deteceted
)的所有列,並用NaN
和 rest 用我需要的隨機數填充不需要的元素,但我不知道我能做到這一點。
這是迄今為止我能做到的最好的:
import numpy as np
import numpy.ma as ma
from scipy.stats import poisson
beta = 0.0048 # Parameter of the PDF
""" Inverse of the time CDF (needed for the Inverse transform method) """
def inverse_time_cdf(x):
return -np.log( (np.exp(-1000*beta)-1)*x + 1 )/beta
""" Simulation of N_sim experiments through the inverse transfrom method """
T = 1000 # Duration of the experiment [s]
rate = 3.945 # [events/s]
lam = rate*T # Poisson distribution parameter
def photon_arrival_simulation(N_sim):
N_detection = poisson.rvs(lam, size = N_sim) # Number of detections in each experiment
t = np.array([inverse_time_cdf(np.random.random(N)) for N in N_detection])
return N_detection, t
如果可能的話,我想避免在photon_arrival_simulation()
function 的列表理解中使用的循環,並且還獲得一個二維數組而不是 arrays 的數組(因為我不能進行數組操作,例如在數組上log
數組)。
我不知道我是否應該在這里或物理堆棧交換中發布這個問題,但提前感謝任何人。
我認為不可能在不循環某處的情況下沿行創建一個長度可變的隨機數組來填充 NaN 值。 但這是解決二維數組問題的方法,您有使用 NaN 的正確想法。 我肯定會在掩碼 arrays 上使用 NaN,因為掩碼 arrays 更多的是為了方便而不是性能。 此外,您應該將文檔字符串放在 function 聲明下方的適當位置。
def photon_arrival_simulation(N_sim):
"""Simulation of N_sim experiments through the inverse transform method"""
N_detection = poisson.rvs(lam, size=N_sim)
rand = np.random.random((len(N_detection), N_detection.max()))
for i, N in enumerate(N_detection):
rand[i, N:] = np.nan
t = inverse_time_cdf(rand)
return N_detection, t
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.