Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the row number in a matching list

I have two list that are not the same length. List (a1) does not have any row number but List b1 does. Im having trouble finding a match in any columns in df1 that match any columns in df2 and return the row number. For example, here is my two list below

df1 = [[2,4,6,8,9,10],[10,13,15,17,26,44],[27,28,34,37,40]]

df2 = [[120,1,2,4,5,6,8],[20,5,6,20,22,23,34],[132,8,12,13,34,45,46],[56,9,10,14,29,32,33],[29,1,22,13,23,33,35],[167,1,6,7,8,9,10],[15,0,2,3,5,6,8]] 

I would like my result like this

result = [[[120,120,120,120],[20,],[132],[56],[56],[167,167,167,167,],[15,15,15]],[[132],[56],[29],[167]],[[20],[132]]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With your example:

df1 = [[2,4,6,8,9,10],[10,13,15,17,26,44],[27,28,34,37,40]] 
df2 = [[120,1,2,4,5,6,8],[20,5,6,20,22,23,34],[132,8,12,13,34,45,46],[56,9,10,14,29,32,33],[29,1,22,13,23,33,35],[167,1,6,7,8,9,10],[15,0,2,3,5,6,8]]

You can do like this:

result = []
for sublist1 in df1:
    row_numbers = []
    for i, sublist2 in enumerate(df2):
        if any(x in sublist2 for x in sublist1):
            row_numbers.append(i)
    result.append([df2[i] for i in row_numbers])

print(result)

Result will be like:

[[[120, 1, 2, 4, 5, 6, 8], [120, 1, 2, 4, 5, 6, 8], [120, 1, 2, 4, 5, 6, 8], [120, 1, 2, 4, 5, 6, 8]],
  [[132, 8, 12, 13, 34, 45, 46], [56, 9, 10, 14, 29, 32, 33], [29, 1, 22, 13, 23, 33, 35], [167, 1, 6, 7, 8, 9, 10]],
  [[20, 5, 6, 20, 22, 23, 34], [132, 8, 12, 13, 34, 45, 46]]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading