2

Given a dataframe such as

df = pd.DataFrame({1: [10,20,30,40], 2: [50,60,70,80], 3: [90,100,110,120], "select": [2, 3, 1, 1])

I can get a series of values selected from each row want to select values in each row corresponding to the column index given in the select column, like this:

df.apply(lambda r: r[r.select], axis=1)   # 50, 100, 30, 40

Is there a better way to do this that doesn't rely on apply?

2 Answers 2

1

Use lookup:

df.lookup(df.index, df['select'])

Output:

array([ 50, 100,  30,  40])
Sign up to request clarification or add additional context in comments.

2 Comments

Now deprecated. Not clear what the new way is of doing this.
@Stuart The link you given has an example of a replacement. This is a result of the discussion here
0

Since DataFrame.lookup is no longer available, something like this (adapted from the docs) seems to be the best way:

def vlookup(df, lookup_series):
    idx, cols = lookup_series.factorize()
    return np.diag(df[cols].to_numpy()[:, idx])

print(vlookup(df, df["select"]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.