I have 4 columns (stimA_pos, stimB_pos, stimC_pos, stimD_pos) of strings defining the positions of images (left, right, up, down). Another column shows the string of the chosen image (decision_resp). I would like to create a new column showing the chosen image instead of 'left', 'right, etc. This should be the result (decision_resp_img):
stimA_pos | stimB_pos | stimC_pos | stimD_pos | decision_resp | decision_resp_img |
---|---|---|---|---|---|
up | left | down | right | left | stimB |
down | up | right | left | down | stimA |
left | down | right | up | right | stimC |
right | left | up | down | down | stimD |
Thanks for any help!
CodePudding user response:
df1.join(df1.reset_index().
melt(['index' ,'decision_resp'], var_name = 'decision_resp_img').
query('decision_resp == value').set_index('index')['decision_resp_img'].
str.replace('_pos', ''))
stimA_pos stimB_pos stimC_pos stimD_pos decision_resp decision_resp_img
0 up left down right left stimB
1 down up right left down stimA
2 left down right up right stimC
3 right left up down down stimD
CodePudding user response:
df["decision_resp_img"] = df.apply(lambda x: dict(zip((a:=dict(x[["stimA_pos","stimB_pos","stimC_pos","stimD_pos"]])).values(), a.keys()))[x["decision_resp"]].replace("_pos","") , axis=1)
df
output:
stimA_pos stimB_pos stimC_pos stimD_pos decision_resp decision_resp_img
0 up left down right left stimB
1 down up right left down stimA
2 left down right up right stimC
3 right left up down down stimD