I have a data frame (df)
df = pd.DataFrame({'No': [123,234,345,456,567,678], 'text': ['60 ABC','1nHG','KL HG','21ABC','K 200','1g HG'], 'reference':['ABC','HG','FL','','200',''], 'result':['','','','','','']}, columns=['No', 'text', 'reference', 'result'])
No text reference result
0 123 60 ABC ABC
1 234 1nHG HG
2 345 KL HG FL
3 456 21ABC
4 567 K 200 200
5 678 1g HG
and a list with elements
list
['ABC','HG','FL','200','CP1']
Now I have the following coding:
for idx, row in df.iterrows():
for item in list:
if row['text'].strip().endswith(item):
if pd.isnull(row['reference']):
df.at[idx, 'result'] = item
elif pd.notnull(row['reference']) and row['reference'] != item:
df.at[idx, 'result'] = 'wrong item'
if pd.isnull(row['result']):
break
I run through df and the list and check for matches.
Output:
No text reference result
0 123 60 ABC ABC
1 234 1nHG HG
2 345 KL HG FL wrong item
3 456 21ABC ABC
4 567 K 200 200
5 678 1g HG HG
The break instruction is important because otherwise a second element could be found within the list and then this second element would overwrite the content in result.
Now I need another solution because the data frame is huge and for loops are inefficient. Think using apply could work but how?
Thank you!