0

I have a column in a dataframe that contain a list inside. My dataframe column is:

 [],
 ['NORM'],
 ['NORM'],
 ['NORM'],
 ['NORM'],
 ['MI', 'STTC'],

As you can see I have an empty list and also a list with two elements. How can I change list with two elements to just take one of it (I don't care which one of it). I tried with df.column.explode()but this just add more rows and I don't want more rows, I just need to take one of it. Thank you so much

0

3 Answers 3

1

You can use Series.map with a custom mapping function which maps the elements of column according to desired requirements:

df['col'] = df['col'].map(lambda l: l[:1])

Result:

# print(df['col'])

0        []
1    [NORM]
2    [NORM]
3    [NORM]
4    [NORM]
5      [MI]
Sign up to request clarification or add additional context in comments.

Comments

1

i, j is the location of the cell you need to access and this will give the first element of the list

list_ = df.loc[i][j]
if len(list_) > 0:
   print(list_[0])

Comments

1

As you store lists into a pandas column, I assume that you do not worry for vectorization. So you could just use a list comprehension:

df[col] = [i[:1] for i in df[col]]

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.