10sha25
10sha25

Reputation: 71

add random elemnt from list to existing dataframe string

I have a dataframe. df['Skill']=python, sql, java. Now for each string I want to add random element (high, low, medium). For Eg: df['Skill']=python:high, sql:low, java:medium.

I have tried one code but it adds score['low', 'high', 'medium'] at the end of the string.

Can someone please suggest how can i do it.

score=['low','medium','high']
df[Skill']=df['Skill'].apply(lambda x:[x + ": " + "".join(w for w in random.choice(score))])

Output:

['python, java, sql: medium']

But i want is python: low, java: high, sql: medium

Upvotes: 0

Views: 64

Answers (2)

I'mahdi
I'mahdi

Reputation: 24049

try this:

import random
skill = ['python','java', 'sql', 'html']
score=['low','medium','high']
select_score = list()
for i in range(len(skill)):
    select_score.append(random.choice(score))

select_score

freq_s = (dict(zip(skill, select_score)))
freq_s

output:

{'python': 'medium', 'java': 'low', 'sql': 'medium', 'html': 'low'}

Upvotes: 1

Satya
Satya

Reputation: 5907

Check this:

df['Skill']= df['Skill'].apply(lambda x:','.join([y+': '+random.choice(score) for y in x.split(',')]))

Upvotes: 1

Related Questions