1

Based on the dataframe (1) below, I wish to create a dataframe (2) where either y or z is equal to 2. Is there a way to do this conveniently?

And if I were to create a dataframe (3) that only contains rows from dataframe (1) but not dataframe (2), how should I approach it?

    id  x  y  z 
    0 324  1  2
    1 213  1  1
    2 529  2  1
    3 347  3  2
    4 109  2  2

...

0

3 Answers 3

2
df[df[['y','z']].eq(2).any(1)]
Out[1205]: 
   id    x  y  z
0   0  324  1  2
2   2  529  2  1
3   3  347  3  2
4   4  109  2  2
Sign up to request clarification or add additional context in comments.

3 Comments

Nice, this would generalise to multiple columns.
Thanks! This method makes a lot of sense, but I am getting an error saying "['y','z'] is not a label or index". Do you know how to fix this?
@csha did you try df[['y','z']]? or can you type list(df) and show you out put here ?
1

You can create df2 easily enough using a condition:

df2 = df1[df1.y.eq(2) | df1.z.eq(2)]

df2
      x  y  z
id           
0   324  1  2
2   529  2  1
3   347  3  2
4   109  2  2

Given df2 and df1, you can perform a set difference operation on the index, like this:

df3 = df1.iloc[df1.index.difference(df2.index)]

df3 
      x  y  z
id           
1   213  1  1

Comments

0

You can do the following:

import pandas as pd

df = pd.read_csv('data.csv')
df2 = df[(df.y == 2) | (df.z == 2)]

print(df2)

Results:

   id    x  y  z
0   0  324  1  2
2   2  529  2  1
3   3  347  3  2
4   4  109  2  2

3 Comments

Please read the existing answers before you post your own, I've already covered this in my answer. stackoverflow.com/a/47360167/4909087
i did not see your answer as I was writing mine. i can remove it though
It's not a problem if it was accidental. Just check before posting :-) It's fine if we post within 1-2 minutes of each other, but the difference between ours is almost 8 minutes.

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.