我正在将一个.csv文件读入一个Pandas Dataframe (CorpActionsDf)。其标题是:
date factor_value reference factor
unique_id
BBG.XAMS.ASML.S 24/04/2015 0.70 Annual Regular Cash
BBG.XAMS.ASML.S 25/04/2014 0.61 Annual Regular Cash
BBG.XAMS.ASML.S 26/04/2013 0.53 Annual Regular Cash
BBG.XAMS.ASML.S 26/11/2012 9.18 None Return of Capital
BBG.XAMS.ASML.S 27/04/2012 0.46 Annual Regular Cash
然后我尝试过滤 Dataframe ,这样我只保留两个日期之间的数据。
startDate=02-01-2008
endDate=20-02-2008
但我得到了以下错误:
TypeError: <class 'datetime.date'> type object 2008-01-02
我有另一个进程,它使用startDate和endDate来过滤信息,但由于某种原因,这次我无法让过滤工作。我的代码如下:
def getCorpActionsData(rawStaticDataPath,startDate,endDate):
pattern = 'CorporateActions'+ '.csv'
staticPath = rawStaticDataPath
with open(staticPath+pattern,'rt') as f:
CorpActionsDf = pd.read_csv(f,engine='c',header=None,usecols=[0,1,2,3,4],parse_dates=[1],
dayfirst=True,index_col=[1],names=['unique_id', 'date','factor_value','reference','factor'])
print(CorpActionsDf.head())
CorpActionsDf = CorpActionsDf[(CorpActionsDf.index >= startDate) & (CorpActionsDf.index <= endDate)]
我将parse_dates设置为等于第1列,所以我不确定我做错了什么。
2条答案
按热度按时间oxf4rvwz1#
我猜你的索引是字符串(对象)类型-因为下面的条件
(CorpActionsDf.index >= startDate)
给你str() >= datetime.date()
错误消息.CorpActionsDf.index.dtype
的输出是什么?确保
startDate
和endDate
具有正确数据类型:vcirk6k62#
您可以尝试先转换
strings
to_datetime
,然后按以下值使用索引:有趣的是,如果使用
strings
,最后一行被省略:编辑:
您必须
sort_index
才能正确选择:truncate
的另一种解决方案: