Extracting dataframe column with multiple conditions on row values

Mahmood Naderan nt_mahmood at yahoo.com
Fri Jan 7 18:07:49 EST 2022


   Hi



   I have a csv file like this



   V0,V1,V2,V3

   4,1,1,1

   6,4,5,2

   2,3,6,7





   And I want to search two rows for a match and find the column. For
   example, I want to search row[0] for 1 and row[1] for 5. The corresponding
   column is V2 (which is the third column). Then I want to return the value
   at row[2] and the found column. The result should be 6 then.



   I can manually extract the specified rows (with index 0 and 1 which are
   fixed) and manually iterate over them like arrays to find a match. Then I



   key1 = 1

   key2 = 5

   row1 = df.iloc[0]              # row=[4,1,1,1]

   row2 = df.iloc[1]              # row=[6,4,5,2]

   for i in range(len(row1)):

       if row1[i] == key1:

           for j in range(len(row2)):

                if row2[j] == key2:

                    res = df.iloc[:,j]

                    print(res)    # 6





   Is there any way to use built-in function for a more efficient code?





   Regards,

   Mahmood




More information about the Python-list mailing list