nandaloo nandaloo - 1 year ago 91
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),

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

"Statically" it's easy:


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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download