7

I have a pandas.DataFrame df1, indexed with a pandas.DateRange object.

If I have a d1 and d2, as datetimes, why does df[d1:d2]not work, and how can I obtain this slice?

2 Answers 2

9

This works:

In [25]: df.ix[d1:d2]
Out[25]: 
                   A         B         C         D
2000-01-10  1.149815  0.686696 -1.230991 -1.610557
2000-01-11 -1.296118 -0.172950 -0.603887  0.383690
2000-01-12 -1.034574 -0.523238  0.626968  0.471755
2000-01-13 -0.193280  1.857499 -0.046383  0.849935
2000-01-14 -1.043492 -0.820525  0.868685 -0.773050
2000-01-17 -1.622019 -0.363992  1.207590  0.577290

cf. http://pandas.pydata.org/pandas-docs/stable/indexing.html#advanced-indexing-with-labels

On first principles df[d1:d2] should work as it does for Series:

In [27]: df['A'][d1:d2]
Out[27]: 
2000-01-10    1.149815
2000-01-11   -1.296118
2000-01-12   -1.034574
2000-01-13   -0.193280
2000-01-14   -1.043492
2000-01-17   -1.622019
Name: A

Creating an issue here: https://github.com/pydata/pandas/issues/946

Sign up to request clarification or add additional context in comments.

Comments

7

Try the truncate method:

df.truncate(before=d1, after=d2)

It won't modify your original df and will return a truncated one.

From docs:

Function truncate a sorted DataFrame / Series before and/or after
some particular dates.

Parameters
----------
before : date
    Truncate before date
after : date
    Truncate after date

Returns
-------
truncated : type of caller

5 Comments

Can you link to a source for this? I'm on pandas.pydata.org/pandas-docs/stable/… and I haven't found the truncate function.
It works, thanks. Is there a reason why the more convenient df[d1:d2] doesnt work?
@Paragon: here's the link to the description of truncate in the current documentation (v0.7.2): pandas.pydata.org/pandas-docs/stable/generated/…
@saroele no reason, just an API oversight. See my answer below-- if someone would contribute some docs about truncate that would be helpful.
@saroele - I believe df[d1:d2] would imply, that both d1 and d2 are contained in the index (just like in lists). before/after doesn't sound that restrictive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.