Predictive Hacks

How To Get Values By Row Based On Column Name in Python

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

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s