I know it is a fundamental question, but I couldn’t solve it. Any help will be appreciated
My list1 has around 1059 values, list2 has around 7 values.
I want to check values in list1 against values in list2, if matches append ‘x’ to list variable, if not matches append ‘y’ to same list variable. So at the end I want size of my list variable to be equal to the size of list1.
import pandas as pd
list1 = pd.read_excel(r"C:UserskukDownloadsDynamodummy.xlsx", sheet_name='Sheet1')
list2 = pd.read_excel(r"C:UserskukDownloadsDynamodummy.xlsx", sheet_name='Sheet2')
list2=((list2.dropna(subset=['Positionsnummer'])).drop_duplicates(subset=['IPositionsnummer'])).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
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 ‘y’ 6 times when it is not matching
- When using continue, appending ‘I don’t know‘ many times.
Please find the image and script in the edited post
I hope this can help to understand my issue.
I have 1058 recordsin list1[ID] which is equal to one 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).
For example: in first iteration when
U1.ST.XXfromlist1[ID]==U1.ST.XXfromlist2['Positionsnummer']thenvalue.append(New Bewehrungehalt) i.e '88888888'
Advertisement
Answer
Example Solution
import pandas as pd
  
list1 = pd.DataFrame()
list2 = pd.DataFrame()
list1['ID'] = range(10)
list1['Bewehrungsgehalt']= range(10)
list2["Positionsnummer"] = [4,5,1,3]
list2['New Bewehrungsgehalt']= [4000, 5000, 1000, 3000] 
 
value = []
for i in range(len(list1["ID"])):
    if list1["ID"][i] in list(list2["Positionsnummer"]):
        new_val = list2[list2["Positionsnummer"]==list1["ID"][i]]["New Bewehrungsgehalt"].tolist()[0]
        value.append(new_val)
    else:
        old_val = list1['Bewehrungsgehalt'][i]
        value.append(old_val)
Output:
[0, 1000, 2, 3000, 4000, 5000, 6, 7, 8, 9]