使用从 pandas 列表中选择的随机值填充数据框的列

Dan*_*ish 2 python numpy python-3.x pandas

我与客户有一个数据框,如下所示。

df:

id      name     
1       john
2       dan
3       sam
Run Code Online (Sandbox Code Playgroud)

另外,我有一个清单

['www.costco.com', 'www.walmart.com']
Run Code Online (Sandbox Code Playgroud)

我想通过从列表中随机选择元素来添加名为domainto的列。df

预期输出:

id      name       domain
1       john       www.walmart.com
2       dan        www.costco.com
3       sam        www.costco.com
Run Code Online (Sandbox Code Playgroud)

注意:由于是随机选择,输出可能与平时不同。

它是从给定的字符串列表中随机选择的,因此它不相同且不重复。这是一个具体的问题,它得到了很好且非常具体的答案。

小智 6

您可以使用random.choices

import random
df['domain'] = random.choices(lst, k=len(df))
Run Code Online (Sandbox Code Playgroud)

输出示例:

   id  name           domain
0   1  john  www.walmart.com
1   2   dan   www.costco.com
2   3   sam   www.costco.com
Run Code Online (Sandbox Code Playgroud)