Conditional concatenation of python pandas dataframe (sql join on self)
Question: **[Aim]**  
We have an existing dataframe and wish to extract a series of records and
concat (sql join on self) given a condition in one command OR in another
DataFrame.

**[Situation]**  
Python version: 3.3.3  
Pandas version: 0.15.1

We have a sizeable DataFrame with 10,000+ rows. This is just an example to
understand the logic.

DataFrame1 -> df1:

    
    
    import pandas as pd
    df1 = pd.DataFrame({'A': [1,2,3,1],
                        'B': [1,4,1,2],
                        'C': ['test1','test2','test3','test4']
                        })
    
    Resulting in:
        A  B      C
        1  1  test1
        2  4  test2
        3  1  test3
        1  2  test4
        5  8  test5
    

**[Expected output]**  
We are looking to output:

  * All columns A, B, C where: B = 1 -> output = df1[df1['B'] == 1]
  * Add to output all of those where   
  
output['A'] == df1['A']  
AND  
df1['B'] == 2  

Thus:

    
    
    A  B      C
    1  1  test1
    3  1  test3
    1  2  test4
    

It would be awesome to show the most pythonic/ pandanic (sounds weird) way of
doing this :)


Answer: Not sure whether there is a better way, but the following works. The idea is
to use `.isin` operator for your 2nd condition. The final boolean selector is
a `or` combination of 1st condition and 2nd condition.

    
    
    import pandas as pd
    import numpy as np
    
    # your data
    # =============================
    df1 = pd.DataFrame({'A': [1,2,3,1],
                        'B': [1,4,1,2],
                        'C': ['test1','test2','test3','test4']
                        })
    print(df1)
    
    
       A  B      C
    0  1  1  test1
    1  2  4  test2
    2  3  1  test3
    3  1  2  test4
    
    # processing
    # =====================================
    mask = df1.B == 1
    
    df1[mask | ((df1.A.isin(df1[mask].A)) & (df1.B==2))]
    
    
       A  B      C
    0  1  1  test1
    2  3  1  test3
    3  1  2  test4
    

