We have provided an example of how to select a column using the column value as column name in R. Let’s do it also in Python:
import pandas as pd import numpy as np df = pd.DataFrame.from_dict({"V1": [66, 57, 79,75], "V2": [41,85,94,71], "V3":[19,3,38,58], "Selection":['V1','V3', 'V2','V3']}) df
V1 V2 V3 Selection
0 66 41 19 V1
1 57 85 3 V3
2 79 94 38 V2
3 75 71 58 V3
We want to get a new column according to the Selection
column, where the first value will be the corresponding value of V1
column the second value will be the corresponding value of V3
column and so on.
Using the lookup function
df['Value'] = df.lookup(df.index, df.Selection) df
V1 V2 V3 Selection Value
0 66 41 19 V1 66
1 57 85 3 V3 3
2 79 94 38 V2 94
3 75 71 58 V3 58
Using the factorize function
idx, cols = pd.factorize(df['Selection']) df['Value'] = df.reindex(cols, axis=1).to_numpy()[np.arange(len(df)), idx] df
V1 V2 V3 Selection Value
0 66 41 19 V1 66
1 57 85 3 V3 3
2 79 94 38 V2 94
3 75 71 58 V3 58