本文介绍了 pandas 按日期过滤值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期数组dateref,想获取pandas数据框数据的值按dateref过滤(仅dateref中包含的日期值):

I have a date array dateref and want to get the values of pandas dataframe datafiltered by dateref (only the values for the dates included in dateref) :

我尝试过此方法,但是它不起作用:

I tried this, but it does not work:

  df: Out[36]: rec.array([ (datetime.date(2007, 4, 10), 105), 

  df[df.date== dateref ]

data.date:日期数组

data.date : array of date

data.value:值的数组

data.value : array of values

这返回错误

data[data.date.isin(dateref)] 
AttributeError: 'numpy.ndarray' object has no attribute 'isin'

推荐答案

我认为您需要 numpy.in1d :

I think you need numpy.in1d:

data[np.in1d(data.date, dateref)] 

示例:

import numpy as np
import datetime as datetime

test = np.array([datetime.date(2007, 4, 10), 
                 datetime.date(2007, 5, 10), 
                 datetime.date(2007, 6, 10)])

states = [datetime.date(2007, 4, 10), 
          datetime.date(2007, 5, 10)]

mask = np.in1d(test, states)
print mask
[ True  True False]

print test[mask]
[datetime.date(2007, 4, 10) datetime.date(2007, 5, 10)]

这篇关于 pandas 按日期过滤值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 22:22