Brian Brian - 8 months ago 36
Python Question

Use series to get at value in dataframe

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
to select elements of
. I want a series of:

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


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


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([[i, s[i]] for i in s.index], s.index)
1000 loops, best of 3: 770 μs per loop