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

标签 python numpy

我有 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/

相关文章:

python - 无法使用numpy loadtxt与python3.6转换日期

python - future 警告 : Using a non-tuple sequence for multidimensional indexing is deprecated use `arr[tuple(seq)]` instead of `arr[seq]`

python - 使 pyplot.hist() 第一个和最后一个 bin 包含离群值

python - 优化Python : Large arrays,内存问题

python - 需要计算校验和方面的帮助

python - 用于在内存中维护表格数据的数据结构?

python - 从 OSX 终端运行 iPython

python - 如何在 "my"python解释器中定义内置函数?

python - Pandas:添加新列,计算此人达到一天最高分的频率

python - Python中的平均最近坐标