如何按日期过滤 numpy.ndarray?
我有一个 2d numpy.array,其中第一列包含 datetime.datetime 对象,第二列包含整数:
A = array([[2002-03-14 19:57:38, 197],
[2002-03-17 16:31:33, 237],
[2002-03-17 16:47:18, 238],
[2002-03-17 18:29:31, 239],
[2002-03-17 20:10:11, 240],
[2002-03-18 16:18:08, 252],
[2002-03-23 23:44:38, 327],
[2002-03-24 09:52:26, 334],
[2002-03-25 16:04:21, 352],
[2002-03-25 18:53:48, 353]], dtype=object)
我想要做的是选择特定日期的所有行,例如
A[first_column.date()==datetime.date(2002,3,17)]
array([[2002-03-17 16:31:33, 237],
[2002-03-17 16:47:18, 238],
[2002-03-17 18:29:31, 239],
[2002-03-17 20:10:11, 240]], dtype=object)
如何实现此目的?
感谢您的见解:)
I have a 2d numpy.array, where the first column contains datetime.datetime objects, and the second column integers:
A = array([[2002-03-14 19:57:38, 197],
[2002-03-17 16:31:33, 237],
[2002-03-17 16:47:18, 238],
[2002-03-17 18:29:31, 239],
[2002-03-17 20:10:11, 240],
[2002-03-18 16:18:08, 252],
[2002-03-23 23:44:38, 327],
[2002-03-24 09:52:26, 334],
[2002-03-25 16:04:21, 352],
[2002-03-25 18:53:48, 353]], dtype=object)
What I would like to do is select all rows for a specific date, something like
A[first_column.date()==datetime.date(2002,3,17)]
array([[2002-03-17 16:31:33, 237],
[2002-03-17 16:47:18, 238],
[2002-03-17 18:29:31, 239],
[2002-03-17 20:10:11, 240]], dtype=object)
How can I achieve this?
Thanks for your insight :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以这样做:
A[:,0]
是A
的第一列。不幸的是,将
A[:,0]
与datetime.date
对象进行比较会引发 TypeError。但是,与datetime.datetime
对象进行比较是有效的:此外,不幸的是,
也会引发 TypeError,因为这会调用
datetime.datetime
的__lt__
方法而不是 numpy 数组的__lt__
方法。也许这是一个错误。无论如何,解决这个问题并不难;你可以说,
既然这给了你一个布尔数组,你可以将它用作
A
的“花哨索引”,这会产生所需的结果。You could do this:
A[:,0]
is the first column ofA
.Unfortunately, comparing
A[:,0]
with adatetime.date
object raises a TypeError. However, comparison with adatetime.datetime
object works:Also, unfortunately,
raises a TypeError too, since this calls
datetime.datetime
's__lt__
method instead of the numpy array's__lt__
method. Perhaps this is a bug.Anyway, it's not hard to work-around; you can say
Since this gives you a boolean array, you can use it as a "fancy index" to
A
, which yields the desired result.