Skip to content
Advertisement

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

Advertisement

Answer

Check this:

df['Skill']= df['Skill'].apply(lambda x:','.join([y+': '+random.choice(score) for y in x.split(',')]))
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement