Home > other >  How to extract array's element from column of arrays?
How to extract array's element from column of arrays?

Time:12-28

I have a dataframe where one of the columns consist of arrays. I need to extract first element from each array in this column. So, for the first row it would be 'classical harp', for 2nd - 'classic persian pop' etc. Here is an example:

enter image description here

And my code below. I tried using lambda along with apply or assign but it doesn't work - I mean I can't take first element of each array in a column:

df = df.assign(top_genre = lambda x: x['genres'][0])
df['new'] = df['genres'].apply(lambda x: x[0])

How to amend my code to make it work properly?

CodePudding user response:

with lambda u can use

df['new'] = df['genres'].apply(lambda x: x.str[0])
  • Related