I am working with the Spotify API in Python and it is returning multiple genres. I am trying to figure out a way to pull the primary genre. Example, the genres brought in our blues, Chicago blues, rythm and blues. I am able to pick out the first one listed and return it in a new column by using the .split method. The issue I am running into now is finding a more efficient way to rename these genres into broader categories (Rock, Blues, etc...)
# Created function to return first genre in list.
d`ef get_first_genre(genre_list):
return genre_list.split(',')[0].strip()`
**# Create a new column "Sub Category" that holds the first genre**
fifties_df['Sub Category'] = fifties_df['Genres'].apply(get_first_genre)
**your text**# Created a new column "Main Genre" that renames the sub category genre into a broader genre category (ex. rockabilly into Rock) by using this method below.
fifties_df.loc[fifties_df['Sub Category'] == 'doo-wop', 'Main Genre'] ='R&B'
fifties_df.loc[fifties_df['Sub Category'] == 'blues', 'Main Genre'] ='Blues'``
fifties_df.loc[fifties_df['Sub Category'] == 'jazz organ', 'Main Genre'] ='Jazz'
fifties_df.loc[fifties_df['Sub Category'] == 'rock-and-roll', 'Main Genre'] ='Rock'
fifties_df.loc[fifties_df['Sub Category'] == 'adult standards', 'Main Genre'] ='Pop'`
You can create a function with if-else and apply in Sub category column
def get_broad_category(sub_category):
if sub_category == 'rock-and-roll':
return "Rock"
elif sub_category == 'blues'
return "Blues"
fifties_df['Category'] = fifties_df['Sub Category'].apply(get_broad_category)