nandaloo nandaloo - 1 month ago 8
Python Question

dynamic indexing using labels in pandas

I would like to dynamically index elements of a pandas DataFrame using labels.
Say I have

df1 = pd.DataFrame(np.random.randn(6, 4),
index=list('abcdef'),
columns=list('ABCD'))


and I want the element with labels 'a' and 'A'.

"Statically" it's easy:

df1.loc['a','A']


But how to do build such a query dynamically at runtime?

indexer = ['a', 'A']
df1.loc[indexer] .... fails!


I don't understand the internals of loc, and what kind of an object it receives/accepts...

Answer

According to the numpy indexing documentation with variable number of indices, it's possible to use a tuple (but not a list) for what I want to do:

In[141]: indexer = ('a', 'A')
In[142]: df1.loc[indexer]
Out[141]: -0.25517278351855893