2

I am trying to search for the row of which contains a string within a list.

df:

           Column1            Out1
0          ['x', 'y']         (0, 2)
1          ['a', 'b']         (3, 0)
etc.

I have attempted the following to search for the row that contains 'a' in a list under Column1, as suggested in this answer:

print df['Column1'].isin(['a'])

With the expectation of such an outcome:

1         ['a', 'b']          (3, 0)

However, I seem to be receiving the following error:

TypeError: unhashable type: 'list'

2 Answers 2

3

Need in for check values in lists:

df = df[df['Column1'].apply(lambda x: 'a' in x)]

Sample:

df = pd.DataFrame({'Column1':[['x','y'], ['a','b']],
                   'Out1':[(0,2), (3,0)]})
print (df)
  Column1    Out1
0  [x, y]  (0, 2)
1  [a, b]  (3, 0)

df1 = df[df['Column1'].apply(lambda x: 'a' in x)]
print (df1)
  Column1    Out1
1  [a, b]  (3, 0)

df1 = df[['a' in x for x in df['Column1']]]
print (df1)
  Column1    Out1
1  [a, b]  (3, 0)
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome. Thanks again! ;)
Is one advantageous over another in any way?
Hard question, second should be a bit faster, but failed if NaNs.
0

What you did in the beginning is correct:

df['Column1'].isin(['a'])

but you to wrap it with square brackets of the same dataframe.

here is an example:

threads = ['1111', '2222', '3333', '4444']
dev_data = train[(train['thread_col'].isin(threads))]

(dev_data) is a dataframe contains the results' rows.

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.