AnalysisNerd
AnalysisNerd

Reputation: 133

Selecting Column values based on dictionary keys

I have a dictionary from which I want decided which columns value I want to choose sort of like an if condition using a dictionary.

     import pandas as pd
     dictname = {'A': 'Select1', 'B':'Select2','C':'Select3'}
     DataFrame = pd.DataFrame([['A',1,2,3,4],['B',1,2,3,4],['B',1,3,4,5],['C',1,5,6,7]], columns=['Name','Score','Select1','Select2','Select3'])

So I want to create a new column called ChosenValue which selects values based on the row value in the column 'Name' e.e. ChosenValue should equal to column 'Select1'' s value if the row value in 'Name' = 'A' and then ChosenValue should equal to 'Select2''s value if the row value in 'Name' = 'B' and so forth. I really want something to link it to the dictionary 'dictname'

Upvotes: 2

Views: 3003

Answers (2)

DSM
DSM

Reputation: 353379

If you know that every Name is in the dictionary, you could use lookup:

In [104]: df["ChosenValue"] = df.lookup(df.index, df.Name.map(dictname))

In [105]: df
Out[105]: 
  Name  Score  Select1  Select2  Select3  ChosenValue
0    A      1        2        3        4            2
1    B      1        2        3        4            3
2    B      1        3        4        5            4
3    C      1        5        6        7            7

Upvotes: 1

cs95
cs95

Reputation: 402852

Use Index.get_indexer to get a list of indices. After that, you can just index into the underlying numpy array.

idx = df.columns.get_indexer(df.Name.map(dictname))
df['ChosenValue'] = df.values[np.arange(len(df)), idx]

df
  Name  Score  Select1  Select2  Select3 ChosenValue
0    A      1        2        3        4           2
1    B      1        2        3        4           3
2    B      1        3        4        5           4
3    C      1        5        6        7           7

Upvotes: 1

Related Questions