cjm2671
cjm2671

Reputation: 19456

Slicing a multiindex on Pandas

I've got a dataframe with a multiindex of the form:

(label, date)

where label is a string and date is a DateTimeIndex.

I want to slice my dataframe by date; say for example, I want to get all the rows between 2007 and 2009:

df.loc[:, '2007':'2009']

It seems like the second part (where I've put the date) is actually slicing the column.

How do I slice on date?

Upvotes: 1

Views: 54

Answers (1)

jezrael
jezrael

Reputation: 862441

You can check partial string indexing:

DatetimeIndex partial string indexing also works on a DataFrame with a MultiIndex:

df = pd.DataFrame(np.random.randn(20, 1),
                  columns=['A'],
                  index=pd.MultiIndex.from_product(
                            [['a', 'b'], pd.date_range('20050101', periods=10, freq='10M'),
                             ]))
idx = pd.IndexSlice
df1 = df.loc[idx[:, '2007':'2009'], :]
print (df1)
                     A
a 2007-07-31  0.325027
  2008-05-31 -1.307117
  2009-03-31 -0.556454
b 2007-07-31  1.808920
  2008-05-31  1.245404
  2009-03-31 -0.425046

Another idea is use loc with axis=0 parameter:

df1 = df.loc(axis=0)[:, '2007':'2009']
print (df1)
                     A
a 2007-07-31  0.325027
  2008-05-31 -1.307117
  2009-03-31 -0.556454
b 2007-07-31  1.808920
  2008-05-31  1.245404
  2009-03-31 -0.425046

Upvotes: 1

Related Questions