Append the -n element in list-series to another list-series if condition met

Viewed 46

I have the following DF (with desired result hardcoded)

dfo = pd.DataFrame({"list1": [["test1", "test2"], ["test1", "test2", "test3"], ["test1", "test2"]], 
                    "list2": [["notatest", "test3"], ["notatest"], ["notatest", "Test3"]],
                    "desired": [["test1", "test2", "test3"], ["test1", "test2", "test3"], ["test1", "test2", "Test3"]]})

In which I want to add/append the very last element of list2 (list2[-1]) to list1 if it == "test3".

Tried the following to no avail:

dfo["list1_test3_added"] = dfo["list1"].apply(lambda x: x.append([i for i in x["list2"][-1] if i == "test3"]))

Could also be the case that at some point someone loses their mind and it's not "test3" but "Test3", so maybe a regex match would be needed.

1 Answers

Test last value converted to lowercase and if match add to one element list and last add to original column list1:

s = dfo["list2"].apply(lambda x: [x[-1]] if x[-1].lower() == "test3" else [])
dfo["list1_test3_added"] = dfo["list1"] + s
print (dfo)
                   list1              list2                desired  \
0         [test1, test2]  [notatest, test3]  [test1, test2, test3]   
1  [test1, test2, test3]         [notatest]  [test1, test2, test3]   
2         [test1, test2]  [notatest, Test3]  [test1, test2, Test3]   

       list1_test3_added  
0  [test1, test2, test3]  
1  [test1, test2, test3]  
2  [test1, test2, Test3]  
Related