Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting pandas dataframe column by row-specific list

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]
like image 583
d_gnz Avatar asked Dec 31 '22 02:12

d_gnz


1 Answers

Just lookup would be fine:

df.lookup(df.index,lst)

#array([ 1,  2, 11,  6,  5], dtype=int64)
like image 199
anky Avatar answered Feb 20 '23 16:02

anky