Charles
Charles

Reputation: 367

selecting a value from a column based on value in another column

I have a not too large DF. I want to add a column that looks up the value in the column of that specific row. So in the example below, the value should come from the column names 'PA1.13'

example

example = {'Honda Civic': [1],
        'Toyota': [0],
        'valuetolookup': ['Honda Civic'],
        'Result should be': [1]
        }

As you can see the column has two levels. I cannot seem to find how to make a second column level from scratch, but here I hope that I can work it out if someone wants to use my example code to solve it :-)

Upvotes: 0

Views: 63

Answers (1)

tdenimal
tdenimal

Reputation: 70

You can use a simple apply() to extract data like you want:

import pandas as pd

example = {'Honda Civic': [1,3],
        'Toyota': [0,2],
        'valuetolookup': ['Honda Civic','Toyota'],
        'Result should be': [1,2]
        }

df = pd.DataFrame(example)


#In the pandas apply, i use the "valuetolookup" column value to get the column name 
df["Result"] = df.apply(lambda x : x[x["valuetolookup"]],axis=1)

I added another row to show you that you can use different columns to lookup :)

Upvotes: 1

Related Questions