gpt4 book ai didi

python - Numpy 随机选择不适用于二维列表

转载 作者:太空狗 更新时间:2023-10-30 02:01:11 25 4
gpt4 key购买 nike

我运行了以下 python 代码:

import numpy as np
a_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]]
np.random.choice(a_list, size=20,
replace=True)

期待这样的结果:

[[7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2], [1, 2, 3], [1, 2, 3], [10, 1, 2], [1, 2, 3], [7, 8, 9], [1, 2, 3], [1, 2, 3], [10, 1, 2], [4, 5, 6], [4, 5, 6], [10, 1, 2], [10, 1, 2], [7, 8, 9], [1, 2, 3], [7, 8, 9]]

但我得到的却是下面的错误信息:

 ValueError                           Traceback (most recent call last)
<ipython-input-80-c11957aca587> in <module>()
2 a_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]]
3 np.random.choice(a_list, size=20,
----> 4 replace=True)

mtrand.pyx in mtrand.RandomState.choice()

ValueError: a must be 1-dimensional

如何从二维列表中随机选择?

最佳答案

您将需要使用索引:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]])
indices = np.arange(arr.shape[0])

output = arr[np.random.choice(indices, 20)]

或者,甚至更短(基于 hpaulj 的评论):

output = arr[np.random.choice(arr.shape[0],20)]

关于python - Numpy 随机选择不适用于二维列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52552864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com