簡體   English   中英

有沒有辦法創建一個數組,該數組的值由另一個數組的值決定?

[英]Is there a way to create an array which values are conditioned by the values of another array?

我有一個名為 E 的值數組,表示能量值

E = np.arange(0.1, 101, 0.1)

我想創建一組名為 a0、a1、a2、a3 的數組,它們是那些根據能量值而變化的系數,所以我想做一些類似的事情:

for item in E:
  if item <= 1.28:
      a3, a2, a1, a0 = 0, -8.6616, 13.879, -12.104 
  elif 1.28<item<10:
      a3, a2, a1, a0 = -0.186, 0.428, 2.831, -8.76
  elif item >=10:
      a3, a2, a1, a0 = 0, -0.0365, 1.206, -4.76

這段代碼不會返回任何錯誤,但我不知道如何創建與 E(能量數組)長度相同的列表或數組,每個數組都包含特定能量值的系數值,所以我真的很感激你的幫助!

此致!

import numpy as np

constants = [[ 0, -8.6616, 13.879, -12.104 ],
             [ 0.186, 0.428, 2.831, -8.76 ],
             [ 0, -0.0365, 1.206, -4.76 ]]

constants = np.array(constants)

E = np.arange(0.1, 101, 0.1)

bins = np.digitize(E, [1.28, 10])

a0 = np.choose(bins, constants[:, 3])
a1 = np.choose(bins, constants[:, 2])
a2 = np.choose(bins, constants[:, 1])
a3 = np.choose(bins, constants[:, 0])

如果你想快速做到這一點,你可以使用布爾數組,如下所示:

bool_array_1 = (E <= 1.28)
bool_array_2 = (E > 1.28) & (E < 10)
bool_array_3 = (E >= 10)

a3 = -0.186 * bool_array_2 
a2 = -8.6616 * bool_array_1 + 0.428 * bool_array_2 + (-0.0365) * bool_array_3 
a1 = 13.879 * bool_array_1 + 2.831 * bool_array_2 + 1.206 * bool_array_3 
a0 = -12.104 * bool_array_1 + (-8.76) * bool_array_2 + (-4.76) * bool_array_3 

例如,如果a = 1.5b = np.array([False, True, False, True]) ,則a * b產生array([0, 1.5, 0, 1.5])

暫無
暫無

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

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