我有 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 - 如何从 numpy 矩阵中随机选择项目(以矢量化方式)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59176008/