python之如何从 numpy 矩阵中随机选择项目(以矢量化方式)

del 阅读:20 2024-11-24 20:56:43 评论:0

我有 numpy 的产品票价矩阵,比如

|--------|---------------------|------------------|------------------|------------------| 
|        |     Product 1       |     Product 2    |     Product 3    |     Product 4    | 
|--------|---------------------|------------------|------------------|------------------| 
| Fare 1 |          10         |         11       |         12       |         13       | 
|--------|---------------------|------------------|------------------|------------------| 
| Fare 2 |          20         |         21       |         22       |         23       | 
|--------|---------------------|------------------|------------------|------------------| 
| Fare 3 |          30         |         31       |         32       |         33       | 
|--------|---------------------|------------------|------------------|------------------| 

我的目标是在连续几天内为每种产品随机选择票价。本质上,我希望有类似的东西

|-------|---------------------|------------------|------------------|------------------| 
|       |     Product 1       |     Product 2    |     Product 3    |     Product 4    | 
|-------|---------------------|------------------|------------------|------------------| 
| Day 1 |          30         |         11       |         22       |         13       | 
|-------|---------------------|------------------|------------------|------------------| 
| Day 2 |          30         |         31       |         22       |         33       | 
|-------|---------------------|------------------|------------------|------------------| 

我想到的唯一方法是使用经典循环:

import numpy as np 
 
generator = np.random.default_rng() 
days = {1, 2} 
fare_product_matrix = np.array([[10, 20, 30], [11, 21 , 31], [12, 22, 32], [13, 23, 33]]) 
 
fare_indexes = generator.integers(0, fare_product_matrix.shape[1], size=(len(days), fare_product_matrix.shape[0])) 
 
out = np.empty(fare_indexes.shape) 
for day in range(len(days)): 
    for product in range(fare_product_matrix.shape[0]): 
        out[day, product] = fare_product_matrix[product, fare_indexes[day, product]] 

是否有任何智能矢量化方法可以用 numpy 做到这一点?

请您参考如下方法:

像这样的东西:

rows = np.random.randint(0,fare_product_matrix.shape[0],  
                        len(days) * fare_product_matrix.shape[1]) 
 
cols = np.tile(np.arange(fare_product_matrix.shape[1]), len(days)) 
 
fare_product_matrix[rows, cols].reshape(len(days), -1) 

输出:

array([[30, 21, 12, 13], 
       [10, 31, 32, 23]]) 


标签:Python
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号