I'm trying to build a series of F.when based on a variable number of conditions. How can I build the logic below using a loop where I supply a list of items to test (i.e. [1,2,3] following the example below)?
The reason I ask is because I want to be able to build these conditions with a variable number of test items in the list.. the loop logic should build something like the below, but by passing a list of numbers to test, [1,2,3].
F.when(F.col("test") == 1, "out_" + str(1) ).when(F.col("test") == 2, "out_" + str(2)).when(F.col("test") == 3, "out_" + str(3)).otherwise(-1)
I've tried to use reduce to do this, but haven't figure this out before. Does anyone have any advice?
reduce(lambda x, i: x.when(F.col("test") == i , "out_" + str(i)),
output_df,
F).otherwise(-1)
My expected output should provide the same logic as the below:
Column<b'CASE WHEN (test = 1) THEN out_1 WHEN (test = 2) THEN out_2 WHEN (test = 3) THEN out_3 ELSE -1 END'>