📜  如何使用 NumPy 从列表中选择不同概率的元素?

📅  最后修改于: 2022-05-13 01:55:08.812000             🧑  作者: Mango

如何使用 NumPy 从列表中选择不同概率的元素?

我们将看到如何使用numpy.random.choice()方法以不同的概率从列表中选择元素。

注:参数p 与 a(1d-array) 中每个条目相关的概率。如果没有给出,样本假设在a中的所有条目上均匀分布。

现在,让我们看看例子:

示例 1:

Python3
# import numpy library
import numpy as np
  
# create a list
num_list = [10, 20, 30, 40, 50]
  
# uniformly select any element
# from the list
number = np.random.choice(num_list)
  
print(number)


Python3
# import numpy library
import numpy as np
  
# create a list
num_list = [10, 20, 30, 40, 50]
  
# choose index number-3rd element
# with 100% probability and other
# elements probability set to 0
# using p parameter of the
# choice() method so only
# 3rd index element selected
# every time in the list size of 3.
number_list = np.random.choice(num_list, 3,
                          p = [0, 0, 0, 1, 0])
  
print(number_list)


Python3
# import numpy library
import numpy as np
  
# create a list
num_list = [10, 20, 30, 40, 50]
  
  
# choose index number 2nd & 3rd element
# with  50%-50% probability and other
# elements probability set to 0
# using p parameter of the
# choice() method so 2nd & 
# 3rd index elements selected
# every time in the list size of 3.
number_list = np.random.choice(num_list, 3,
                          p = [0, 0, 0.5, 0.5, 0])
  
print(number_list)


输出:

50

示例 2:

蟒蛇3

# import numpy library
import numpy as np
  
# create a list
num_list = [10, 20, 30, 40, 50]
  
# choose index number-3rd element
# with 100% probability and other
# elements probability set to 0
# using p parameter of the
# choice() method so only
# 3rd index element selected
# every time in the list size of 3.
number_list = np.random.choice(num_list, 3,
                          p = [0, 0, 0, 1, 0])
  
print(number_list)

输出:

[40 40 40]

在上面的例子中,我们只想每次都从给定的列表中选择第 3 个索引元素。

示例 3:

蟒蛇3

# import numpy library
import numpy as np
  
# create a list
num_list = [10, 20, 30, 40, 50]
  
  
# choose index number 2nd & 3rd element
# with  50%-50% probability and other
# elements probability set to 0
# using p parameter of the
# choice() method so 2nd & 
# 3rd index elements selected
# every time in the list size of 3.
number_list = np.random.choice(num_list, 3,
                          p = [0, 0, 0.5, 0.5, 0])
  
print(number_list)

输出:

[30 40 30]

在上面的例子中,我们希望每次都从给定的列表中选择第 2 个和第 3 个索引元素。