Use .loc by default for Pandas dataframe

Viewed 76

I know the common methods to accesss index / columns in a Pandas dataframe (see also indexing guide):

  • df.iloc[..., ...] for integer location
  • df.loc[..., ...] for label-based location
  • df.ix (deprecated)
  • df['C1'] or df.C1 for column access
  • df['mylabel1':'mylabel10'] or df[2:7] for row slice access, but df['mylabel1'] and df[2] obviously don't work

I have always found the two last bullet points confusing, since we use the same notation df[...] for both column access or row access.

Question: is there a way to configure Pandas (or a subclass of DataFrame) that simplifies everything such that:

df[...] is in fact an alias for df.loc[...]

?

Example:

import numpy as np
import pandas as pd
x = pd.DataFrame(columns=['C1', 'C1', 'C2'])
x.loc['a'] = [np.random.rand(2000, 500), np.random.rand(2000, 500), np.random.rand(2000)]
print(x.loc['a', 'C2'])
x['a', 'C2']       # should give the same thing, so that by default, x[...] is the same as x.loc[...]
1 Answers

Every expression in Python has an object as a result, so you can assign it to a name:

xl=x.loc
xl['a']=…           # equivalent to x.loc['a']=…

You can't emulate x.loc=… this way, since assigning to xl will simply rebind the name; that's probably irrelevant here, but for completeness the only way to (slightly) shorten such things is to write something like

class Setter:
  def __init__(self,x): self.x=x
  def __getattr__(self,n):
    return lambda(v): setattr(self.x,n,v)
xset=Setter(x).loc
xset(…)             # equivalent to x.loc=…

If you want to have one name that still supports other access modes, you can write a wrapper class:

class DFLoc:
  def __init__(self,x): self.x=x
  def __getitem__(self,k): return self.x.loc[k]
  def __getattr__(self,n): return getattr(self.x,n)

This approach also allows you to support libraries that rely on the fact that a constructed result from something like x.loc is used only once with __setitem__ afterwards. (This would generally be a bug in such libraries, although in some cases the value of such a computed attribute would depend on the changes made through it.)

Related