0

One of the columns in my dataframe is a list. Here is what it looks like -

Column1 Column2
1 ['a','b']
2 ['b']

I want to remove the string b from the list in Column2. I am trying the following -

df=df['Column2'].map(lambda x: if 'b' in x then x.remove('b'))

Can someone please help me out?

1
  • Wrong dupe, so reopened. Commented May 24, 2021 at 6:59

1 Answer 1

1

Change logic - filter all values if not b:

df['Column2']=df['Column2'].map(lambda x: [y for y in x if y != 'b'])

Or:

df['Column2']=df['Column2'].map(lambda x: list(filter(lambda y: y!= 'b', x)))

print (df)
   Column1 Column2
0        1     [a]
1        2      []

Pandas solution possible, more complicated, so slowier:

df['Column2']=df['Column2'].explode().loc[lambda x: x != 'b'].groupby(level=0).agg(list).reindex(df.index, fill_value=[])
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.