0

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

5
  • lambda x: " ".join(w": "+s for w, s in zip(x.split(' '), random.choice(score, x.count(' ')))) you have to apply on each word by splitting Commented Aug 11, 2021 at 11:14
  • df['Skills']= d['Skills'].apply(lambda x: ", ".join(w +": "+s for w, s in zip(x.split(', '), random.choice(score)))) output I get is --- python: l , java: o, sql: w Commented Aug 11, 2021 at 11:35
  • Is there a value sql: medium in your 'Skill' column or apply() is giving out this result? Commented Aug 11, 2021 at 11:39
  • I tried map and apply. both are giving me the same result Commented Aug 11, 2021 at 11:43
  • There is no [sql: medium] in the skill column only [sql] is present in the skill column output I get is using apply function Commented Aug 11, 2021 at 11:49

2 Answers 2

1

Check this:

df['Skill']= df['Skill'].apply(lambda x:','.join([y+': '+random.choice(score) for y in x.split(',')]))
Sign up to request clarification or add additional context in comments.

3 Comments

'Series' object has no attribute 'split' this is the error I get
sorry i used variable name x inside the apply function, edited it, check now
Yes, I understood the error also understood the logic and I have resolved my problem Thankyou.
1

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'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.