Fill the column of a dataframe with random values chosen from a list in pandas

Question:

I have a data frame with the customers as shown below.

df:

id      name     
1       john
2       dan
3       sam

also, I have a list as

['www.costco.com', 'www.walmart.com']

I would like to add a column named domain to df by randomly selecting the elements from the list.

Expected output:

id      name       domain
1       john       www.walmart.com
2       dan        www.costco.com
3       sam        www.costco.com

Note: since it is a random selection output may not be the same as always.

It is randomly selecting from the given list of strings, hence it is not same and not duplicate. And it is a specific question and it got great and very specific answers.

Asked By: Danish

||

Answers:

You can use random.choices:

import random
df['domain'] = random.choices(lst, k=len(df))

A sample output:

   id  name           domain
0   1  john  www.walmart.com
1   2   dan   www.costco.com
2   3   sam   www.costco.com
Answered By: user7864386
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.