3

Let's say this is my df

   A     B
0  a  (33,32)
1  b  (44,33)
2  a  32
3  a  (66,33)
4  b  (77,34,12)
5  c  (88,1,55)

where column B values are tuples and I need to get something like df[df['B']contain 33]

   A     B
0  a  (33,32)
1  b  (44,33)
3  a  (66,33)

is there any way to achieve this?

1 Answer 1

2

If there is mix numbers with tuples first convert integers to tuples:

df['B'] = df['B'].apply(lambda x: x if isinstance(x, tuple) else (x,))

And then filter values in tuples like:

df = df[df.B.apply(lambda x: 33 in x)]

Or:

df = df[[33 in x for x in df.B]]

Or:

df = df[pd.DataFrame(df.B.tolist()).eq(33).any(axis=1)]

print (df)
   A         B
0  a  (33, 32)
1  b  (44, 33)
3  a  (66, 33)
Sign up to request clarification or add additional context in comments.

6 Comments

Thx @jezrael ! But i get this error: argument of type 'int' is not iterable
@Jeff - so there is mix tuples with integers?
@Jeff - I think (32,) is (32) ? Because one element tuple is defined with comma like (value, )
yes i just realised the column have int as well, actually the column is convert from another column with string values eg. '33,32', '33', .... etc. using literal_eval. Do you have any advice?
@Jeff - Its happens, first I think it was typo, so edited question first time ;)
|

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.