0

My dataframe looks like

Name score
A;A;B 5
C;C;A 6

I want to make it without using any for loop

Name  score
A  5
B  5
C  6
A  6

Please help. Thanks in advance.

1 Answer 1

1

Use DataFrame.explode with splitted values by ; and then DataFrame.drop_duplicates:

df = (df.assign(Name = df['Name'].str.split(';'))
        .explode('Name')
        .drop_duplicates(['Name','score'], ignore_index=True))
print (df)
  Name  score
0    A      5
1    B      5
2    C      6
3    A      6
Sign up to request clarification or add additional context in comments.

8 Comments

Not working. It is adding one column, but not appending new rows.
@user10340258 - what is print (df.head().to_dict()) ?
it worked for test dataframe, but not for the real dataframe. not clear to me. Anyways, thanks for your help.
@user10340258 - what is difference with real data?
your code has worked with the real data also. I only renamed the columns. Earlier column names contained underscores which I removed. It is not clear to me why underscore mattered. Anyways, thanks a lot.
|

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.