python - Numpy / Pandas:从列表中随机选择 n 个项目,其中 n 是随机整数,对于每个索引
问题描述
我是 numpy 和 pandas 的新手,我正在尝试编写这段代码来创建一个 pandas 系列。对于系列中的每个索引,我想从上面的列表中随机选择一个随机数量的兴趣,在这种情况下为 1 - 3,没有重复。如果可能的话,我想找到改进我的代码的方法。
谢谢
def random_interests(num):
interests = [1, 2, 3, 4, 5, 6]
stu_interests = []
for n in range(num):
stu_interests.append(np.random.choice(interests, np.random.randint(1, 4), replace=False))
rand_interests = pd.Series(stu_interests)
解决方案
您必须在函数中添加一个返回值,以便从中获得结果。通过在底部添加返回,您的代码将是:
def random_interests(num):
interests = [1, 2, 3, 4, 5, 6]
stu_interests = []
for n in range(num):
stu_interests.append(np.random.choice(interests, np.random.randint(1, 4), replace=False))
rand_interests = pd.Series(stu_interests)
return rand_interests
通过运行 n=5 输出是:
random_interests(5)
0 [5, 6, 4]
1 [5]
2 [1, 6, 4]
3 [3, 4, 1]
4 [1, 2]
dtype: object
推荐阅读
- photoshop - 如何在 Photoshop (UXP) 中绘制路径?
- sms - SMPP 客户端连接但不发送短信
- angular - Fullcalendar 角度不同日期的不同 maxtime
- linux - 如何在 google chrome ubunutu 中允许默认的 xdg-open 应用程序
- c++ - 为派生类重载输出/输入运算符时,在派生类对象上调用基类方法是否正确?
- mulesoft - 从对象存储中检索值 Mulesoft
- android - 获取文件路径的所有子文件夹android kotlin
- elasticsearch - 应用聚合后过滤掉弹性搜索中的术语聚合桶
- c# - Linq 查询要么给我重复记录,要么只给我一条记录
- html - Django 模板语法错误(无效的块标签)