5

For each row in a dataframe, I'm trying to select the column, which is specified in a list. The list has the same length as the dataframe has rows.

df = pd.DataFrame({"a":[1,2,3,4,5], 
                   "b":[3,4,5,6,7], 
                   "c":[9,10,11,12,13]})
lst = ["a","a","c","b","a"]

The result would look like this:

[1,2,11,6,5]

2 Answers 2

8

Just lookup would be fine:

df.lookup(df.index,lst)

#array([ 1,  2, 11,  6,  5], dtype=int64)
Sign up to request clarification or add additional context in comments.

Comments

3

lookup should be the way, but try something diff

df.stack().reindex(pd.MultiIndex.from_arrays([df.index,lst])).values
array([ 1,  2, 11,  6,  5])

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.