【问题标题】:Is there a way to create an array which values are conditioned by the values of another array?有没有办法创建一个数组,其值由另一个数组的值决定?
【发布时间】:2021-07-13 07:51:04
【问题描述】:

我有一个名为 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(能量数组)长度相同的列表或数组,每个数组都包含特定能量值的系数值,所以我非常感谢您的帮助!

最好的问候!

【问题讨论】:

  • 使用a0 = [] ... a0.append(new_value)

标签: python arrays if-statement coefficients energy


【解决方案1】:
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])

【讨论】:

  • 解决这个问题的好方法,我之前从未听说过numpy的digitize函数!
  • 哇,谢谢!解决这个问题的好方法,感谢您的帮助! :)
【解决方案2】:

如果你想快速做到这一点,你可以使用布尔数组,如下所示:

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])

【讨论】:

  • 感谢您的帮助!我很感激:)
猜你喜欢
  • 2021-07-29
  • 1970-01-01
  • 2020-11-19
  • 2021-02-28
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多