pandas 如何使用日期时间对数据框进行切片?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9788299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to perform slicing of a data frame using datetimes?
提问by saroele
I have a pandas.DataFramedf1, indexed with a pandas.DateRangeobject.
我有一个pandas.DataFramedf1, 用一个pandas.DateRange对象索引。
If I have a d1and d2, as datetimes, why does df[d1:d2]not work, and how can I obtain this slice?
如果我有一个d1andd2作为日期时间,为什么不起作用df[d1:d2],我怎样才能获得这个切片?
回答by Wes McKinney
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
参见 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:
首要原则df[d1:d2]应该像系列一样工作:
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
回答by eumiro
Try the truncatemethod:
试试truncate方法:
df.truncate(before=d1, after=d2)
It won't modify your original dfand will return a truncated one.
它不会修改您的原始文件df,而是返回一个截断的文件。
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

