DEV Community

Kuladeep561
Kuladeep561

Posted on

Lookup for a value in a column and get another value in python pandas

Hello Everyone,

I know it is a fundamental question, but I couldn't solve it.
Any help will be appreciated

@ralphbrooks , @julienkervizic adding you to get quick response!! Please excuse me.

I hope this can help to understand my issue.

(Plese find the image below)
I have total 1058 records in list1[ID] which has matching records in list2['Positionnummer'].
So when both equals I want to get corresponding value from list2['New Bewehrungsgehalt'] and append to out output list i.e value, if not equal append old(default) value to the list value.
At the end I want len(list1) == len(value) i.e 1058.

For example: in first iteration when U1.ST.XX from list1[ID] ==
U1.ST.XX from list2['Positionsnummer'] then value.append(New
Bewehrungehalt) i.e '88888888'
, if not matching append the default value.

import pandas as pd

list1 = pd.read_excel(r"C:\Users\kuk\Downloads\Dynamo\dummy.xlsx", sheet_name='Sheet1')
list2 = pd.read_excel(r"C:\Users\kuk\Downloads\Dynamo\dummy.xlsx", sheet_name='Sheet2')

list2=((list2.dropna(subset=['Positionsnummer'])).drop_duplicates(subset=['Positionsnummer'])).reset_index()

value=[]
for i in range(len(list1)):

    for j in range(len(list2)):
        if list1["ID"][i] == list2["Positionsnummer"][j]:
            value.append(list2['New Bewehrungsgehalt'])
            break
        else:
            value.append(list2['Bewehrungsgehalt'])
            break
Enter fullscreen mode Exit fullscreen mode

But I am not getting as I wanted. I tried using break, continue everything, but it is not working.

  • When using break, it's appending 6 times when it is not matching
  • When using continue, appending 'I don't know' many times.

Please find the image here

Top comments (1)

Collapse
 
wpeterw profile image
wpeterw

I think this is helpfull: stackoverflow.com/questions/593061...