Pandas: Check if row exists with certain values

前端 未结 3 1574
失恋的感觉
失恋的感觉 2020-12-25 10:24

I have a two dimensional (or more) pandas DataFrame like this:

>>> import pandas as pd
>>> df = pd.DataFrame([[0,1],[2,3],[4,5]], columns=[         


        
相关标签:
3条回答
  • 2020-12-25 10:38

    Turns out it is really easy, the following does the job here:

    >>> ((df['A'] == 2) & (df['B'] == 3)).any()
    True
    >>> ((df['A'] == 1) & (df['B'] == 2)).any()
    False
    

    Maybe somebody comes up with a better solution which allows directly passing in the array and the list of columns to match.

    Note that the parenthesis around df['A'] == 2 are not optional since the & operator binds just as strong as the == operator.

    0 讨论(0)
  • 2020-12-25 10:50

    an easier way is:

    a = np.array([2,3])
    (df == a).all(1).any()
    
    0 讨论(0)
  • 2020-12-25 10:52

    If you also want to return the index where the matches occurred:

    index_list = df[(df['A'] == 2)&(df['B'] == 3)].index.tolist()
    
    0 讨论(0)
提交回复
热议问题