Brian - 1 year ago 88

Python Question

I have a series and dataframe

`s = pd.Series(['x', 'y', 'z'], ['a', 'b', 'c'])`

df = pd.DataFrame(np.arange(9).reshape(3, 3), s.index, s.values)

I want to use

`s`

`df`

`[df.loc['a', 'x'], df.loc['b', 'y'], df.loc['c', 'z']]`

Answer Source

You can use `lookup`

:

```
df.lookup(s.index, s.values)
[0 4 8]
```

Or as a pandas.Series:

```
pd.Series(df.lookup(s.index, s.values), s.index)
a 0
b 4
c 8
```

**Timings**

Using larger data than what's in the question:

```
from string import ascii_lowercase, ascii_uppercase
s = pd.Series(list(ascii_lowercase), list(ascii_uppercase))
df = pd.DataFrame(np.arange(26**2).reshape(26, 26), s.index, s.values)
```

Yields the following timings:

```
%timeit pd.Series(df.lookup(s.index, s.values), s.index)
1000 loops, best of 3: 241 μs per loop
%timeit pd.Series([df.at[i, s[i]] for i in s.index], s.index)
1000 loops, best of 3: 770 μs per loop
```