根据日期分割资料框 [英] Split dataframe on the basis of date
问题描述
我正在尝试根据日期将数据框分为两部分.此处已解决了一个相关问题:将数据帧拆分为两个根据日期
I am trying to split a dataframe into two based on date. This has been solved for a related problem here: Split dataframe into two on the basis of date
我的数据框如下:
abcde col_b
2008-04-10 0.041913 0.227050
2008-04-11 0.041372 0.228116
2008-04-12 0.040835 0.229199
2008-04-13 0.040300 0.230301
2008-04-14 0.039770 0.231421
如何根据日期(例如2008-04-12之前和之后)拆分它?当我尝试这个:
How do I split it based on date (say before 2008-04-12 and after)? When I try this:
df.loc[pd.to_datetime(df.index) <= split_date]
split_date
是datetime.date(2008-04-12)
的地方,出现此错误:
where split_date
is datetime.date(2008-04-12)
, I get this error:
*** TypeError: <class 'datetime.date'> type object 2008-04-12
推荐答案
来自您的代码
其中split_date是datetime.date(2008-04-12),我收到此错误
where split_date is datetime.date(2008-04-12), I get this error
此处datetime.date()
将参数设为2008,4,12
格式更多信息 .所以你应该写
here datetime.date()
takes argument as format 2008,4,12
for more. so you should write
split_date = datetime.date(2008,4,12)
当您对输入进行采样时,第一列没有名称,因此您可以按照以下方式访问第一列
and as you sample input the first column has no name so you can follow to access the first column like this
df[(pd.to_datetime(df[df.columns[0]]) < split_date)]
否则,您将列名称指定为"date"
或任意
else you give the column name as "date"
or whatever you want
df[(pd.to_datetime(df["date"]) < split_date)]
最后
TypeError: <class 'datetime.date'> type object 2008-04-12
这基本上是发生的,您可以尝试将此datetime object
应用于df
This is occurred basically you try this datetime object
to the series of df
这篇关于根据日期分割资料框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!