Split dataframe into two on the basis of date

不想你离开。 提交于 2020-01-03 16:44:11

问题


I have dataset with 1000 rows like this

 Date,      Cost,         Quantity(in ton),    Source,          Unloading Station
    01/10/2015, 7,            5.416,               XYZ,           ABC

i want to split the data on the base of date. For e.g. till date 20.12.2016 is a training data and after that it is test data.

How should i split? Is it possible?


回答1:


You can easily do that by converting your column to pandas to_datetime type and set it as index.

import pandas as pd
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index(df['Date'])
df = df.sort_index()

Once you have your data in this format, you can simply use date as index for creating partition as follows:

# create train test partition
train = df['2015-01-10':'2016-12-20']
test  = df['2016-12-21':]
print('Train Dataset:',train.shape)
print('Test Dataset:',test.shape)



回答2:


assuming that your data set is pandas data frame and that Date column is of datetime dtype:

split_date = pd.datetime(2016,12,20)

df_training = df.loc[df['Date'] <= split_date]
df_test = df.loc[df['Date'] > split_date]


来源:https://stackoverflow.com/questions/37532098/split-dataframe-into-two-on-the-basis-of-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!