Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform slicing of a data frame using datetimes?

Tags:

python

pandas

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?

like image 851
saroele Avatar asked Mar 20 '12 14:03

saroele


2 Answers

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

like image 102
Wes McKinney Avatar answered Oct 01 '22 10:10

Wes McKinney


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
like image 40
eumiro Avatar answered Oct 01 '22 12:10

eumiro