2

I am trying to select different columns in a pandas dataframe using selection key

Let us say my dataframe is,

import pandas as pnd
s1 = pnd.Series ([0,3,6,7])
s2 = pnd.Series ([1,4,8,9])
s3 = pnd.Series ([2,5,10,11])
df = pnd.DataFrame({'A':s1, 'B':s2, 'C':s3})

   A  B   C
0  0  1   2
1  3  4   5
2  6  8  10
3  7  9  11

and my selection key is,

s4 = pnd.Series (['A','B','C','A'])


0    A
1    B
2    C
3    A

My desired result is,

0  0
1  4
2  10
3  7

I guess I could run a for loop to do this

l = []
for idx in df.index:
    l.append( df[s4[idx]][idx])
s5 = pnd.Series(l)
print s5

Is there a better/shorter/more efficient way?

1
  • df.stack().ix[zip(s4.index, s4)] ?, but you'll get a multi level index, not sure if that's OK Commented Feb 27, 2013 at 22:43

1 Answer 1

6
pnd.Series(df.lookup(df.index, s4), df.index)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.