0

I have a Pandas dataframe that looks like this

>> pd.DataFrame({'A': [1,2,3], 'B':[4,5,6], 'C':[7,8,9]})

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

I want to select values 1,6,8 that correspond to index-column pairs (0,'A'),(2,'B'),(1,'C'). How do I simultaneously select them?

GingerBadger
  • 300
  • 3
  • 10

1 Answers1

3

Use lookup:

import pandas as pd

df = pd.DataFrame({'A': [1,2,3], 'B':[4,5,6], 'C':[7,8,9]})

rows, cols = zip(*[(0,'A'),(2,'B'),(1,'C')])

result = df.lookup(rows, cols)
print(result)

Output

[1 6 8]
Dani Mesejo
  • 55,057
  • 6
  • 42
  • 65
  • 1
    Probably mostly a matter of taste... but in cases like this, I find it useful to keep `idx = [(0,'A'),(2,'B'),(1,'C')]` or something around so it can be referred to or mutated later and re-used, then just inline it to lookup, so you can then just do a general, `result = df.lookup(*zip(*idx))`... – Jon Clements Jan 01 '19 at 16:33