Selecting pandas dataframe column by row-specific list

Viewed 52

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

Just lookup would be fine:

df.lookup(df.index,lst)

#array([ 1,  2, 11,  6,  5], dtype=int64)

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])
Related