Is there a way to "search" in a pandas DataFrame for 2 specific numbers in the columns and return the index if it exists?

I have a DataFrame using pandas and want to know if there is a way to "search" for 2 specific numbers in rows of specific columns and then return the row

eg

eg

if a = 4 and b = 6 return 1 (index)

or if b = 5 and c = 2 return 2 (index)

or looking into = 2 and b = 1 will return nothing. (since it doesn't exist)

Thank!

+3


source to share


2 answers


print(df.loc[(df["A"] == 4) & (df["B"] == 6)].index[0])

      

In function:

def pairs(df, k1,k2, a, b):
    check = df.loc[(df[k1] == a) & (df[k2] == b)]
    return None if check.empty else check.index[0]

      

Running on your df:



In [5]: pairs(df,"A","B",4,6)
Out[5]: 1

In [6]: pairs(df,"B","C",5,2 )
Out[6]: 2

In [7]: print(pairs(df,"A","B",2,1))
None

      

If you want all indexes to use index.tolist:

def pairs(df, k1,k2, a, b):
    check = df.loc[(df[k1] == a) & (df[k2] == b)]
    return None if check.empty else check.index.tolist()

      

+1


source


Perhaps not the most efficient way, so please feel free to correct me, but.

def find (a, b):



n = 0 
while n < len(df.index):
    if df.iloc[n]['a'] == a and df.iloc[n]['b'] == b:
        print n
    n += 1

      

+1


source







All Articles