Extract row value based on matching column name and column value

Solution 1:

You can still use DataFrame.lookup, you are getting error because the columns in your dataframe are labels with string type while the values in the Cluster column are of int type, so using lookup in such case will throw a KeyError. So in order to resolve this problem, change the dtype of Cluster column to str while using lookup:

df['z'] = df.lookup(df.index, df['Cluster'].astype(str))

# print(df)
   Cluster      0      1      z
0        1  0.212  0.111  0.111
1        0  0.233  0.122  0.233
2        1  0.222  0.123  0.123

Solution 2:

This is one approach using apply.

Ex:

x = [1, 0.212, 0.111]
y = [0, 0.233, 0.122]
z = [1, 0.222, 0.123]
df = pd.DataFrame([x,y,z], columns=["Cluster","0","1"])

df['Cluster'] = df['Cluster'].astype(int).astype(str)
df['Z'] = df.apply(lambda x:  x[x['Cluster']], axis = 1)

print(df)

Output:

  Cluster      0      1      Z
0       1  0.212  0.111  0.111
1       0  0.233  0.122  0.233
2       1  0.222  0.123  0.123