0

I try to split a column of text strings which contains comma-separated values (Genres by Song). For further analysis I need every value of the string in a new row. I am new to python. Managed to import the excel in a pandas dataframe. Couldn't find an example of my problem on stack.

df:

Song Title Genres Length
Song1 HipHop, Rap 3:30
Song2 Rock, Metal,Hard Rock 2:55
Song3 Jazz 4:00

What I try to achieve:

Song Title Genres Length
Song1 HipHop 3:30
Song1 Rap 3:30
Song2 Rock 2:55
Song2 Metal 2:55
Song2 Hard Rock 2:55
Song3 Jazz 4:00

1 Answer 1

2

Perfect job for explode:

df["Genres"] = df["Genres"].apply(lambda g: g.split(","))
df = df.explode("Genres")

# To avoid surprise down the road, remove
# leading and trailing spaces with strip
df["Genres"] = df["Genres"].str.strip()
Sign up to request clarification or add additional context in comments.

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.