按日期将数据框分割

5
我正在尝试根据日期将数据帧拆分为两个部分。这个问题在这里的相关问题中已经解决: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日之前和之后)?当我尝试这样做:

df.loc[pd.to_datetime(df.index) <= split_date]

split_datedatetime.date(2008-04-12) 时,我会收到以下错误:

*** TypeError: <class 'datetime.date'> type object 2008-04-12
3个回答

5

从您的代码

当split_date为datetime.date(2008-04-12)时,我会得到这个错误

在这里,datetime.date()需要以格式2008,4,12作为参数(更多信息)。因此你应该写成:

split_date = datetime.date(2008,4,12)

在您的样例输入中,第一列没有名称,因此您可以按照以下方式访问第一列:

df[(pd.to_datetime(df[df.columns[0]]) < split_date)]

否则,您可以将列名指定为"date"或任何您想要的名称。
df[(pd.to_datetime(df["date"]) < split_date)]

最后

TypeError: <class 'datetime.date'> type object 2008-04-12

当你尝试将这个 datetime 对象 应用于 df 的序列时,就会发生这种情况。

更多信息请见


虽然这个链接可能回答了问题,但最好在此处包含答案的基本部分并提供参考链接。如果链接页面更改,仅链接的答案可能会失效。-【来自审查】 - Lundin
一些解释会很好。 - Sergio Tulentsev
1
(@Lundin和@Sergio),感谢你们的好建议,我会记住在所有下一步方法中使用。 - R.A.Munna
这个代码可以运行,但是会抛出警告:"FutureWarning: Comparing Series of datetimes with 'datetime.date'. Currently, the 'datetime.date' is coerced to a datetime. In the future pandas will not coerce, and a TypeError will be raised. To retain the current behavior, convert the 'datetime.date' to a datetime with 'pd.Timestamp'. split_date = datetime.date(2008,4,12)" - R. Cox

1
这里有一个解决方案: 在数据文件的第一列中添加标签“日期”。
import pandas as pd
df = pd.read_csv('data.csv')

split_date ='2008-04-12'
df_training = df.loc[df['Date'] <= split_date]
df_test = df.loc[df['Date'] > split_date]
print df_test

当你进行比较时,比如说:
df.loc[pd.to_datetime(df.index) <= split_date]

两边必须是相同的类型。

(保留了HTML标签)

1

如果你想获取两个日期之间的数据帧,可以按照 @R.A.Munna 的逻辑进行操作:

import datetime

split_date_one = datetime.date(2019,9,26)
split_date_two = datetime.date(2019,10,13)

df= df[(pd.to_datetime(df[df.columns[0]]) >= split_date_one) & (pd.to_datetime(df[df.columns[0]]) <= split_date_two)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接