nandaloo
nandaloo

Reputation: 1027

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...

Upvotes: 0

Views: 1853

Answers (2)

nandaloo
nandaloo

Reputation: 1027

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

Upvotes: 0

piRSquared
piRSquared

Reputation: 294218

try this instead

df1.loc[indexer[0], indexer[1]]

Upvotes: 1

Related Questions