1

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?

4
  • 1
    df['new'] = df['genres'].str[0] Commented Dec 27, 2022 at 14:49
  • can I use lambda in this case? if so what's wrong with my code? Commented Dec 27, 2022 at 14:56
  • hard to debug your code with an image as input, you must provide a reproducible input Commented Dec 27, 2022 at 15:01
  • I tried it with my dataset (genres column): kaggle.com/datasets/lehaknarnauli/…. However, I got error. Don't know how to overcome it Commented Dec 27, 2022 at 17:30

1 Answer 1

1

with lambda u can use

df['new'] = df['genres'].apply(lambda x: x.str[0])
Sign up to request clarification or add additional context in comments.

2 Comments

it doesn't work with my dataset, it's publicly available: kaggle.com/datasets/lehaknarnauli/…. I can't retrieve first element from 'genres' column. I tried your code and get 'str' object has no attribute 'str' error. I also tried this: df['new'] = df['genres'].apply(lambda x: '[]' if not x else x[0]) - unfortunately I got [ as an outcome. Do you know why it happens?
can your print df['genres'] to see because it work for me

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.