【问题标题】:How to split dataset as train and test data into rows using date, pandas and python?如何使用 date、pandas 和 python 将数据集拆分为训练数据和测试数据成行?
【发布时间】:2020-09-20 18:03:32
【问题描述】:

如何将数据集拆分为训练数据并将测试数据拆分为使用日期的行,例如前 90%(从 2018-01-01 到 2019-02-01)将是训练数据和最后 10%(从 2019-02-02)将是python中的测试数据?不随机分裂?

【问题讨论】:

  • 我相信这个df_train = df[df['date'] < '2019-02-01'] 和这个df_test = df[df['date'] > '2019-02-02'] 应该可以解决问题
  • @Louis this code --> from sklearn.model_selection import train_test_split train_features, test_features, train_labels,test_labels = train_test_split(features, labels,test_size = 0.25, random_state = 42)拆分数据,我想要类似的东西,但使用日期拆分数据。
  • 如果您按日期订购数据框,然后使用 sklearn.train_test_split 并将参数 shuffle 设置为 False 它应该可以让您获得所需的结果。

标签: python pandas data-science random-forest


【解决方案1】:

如果您的数据已经在 pandas 数据框中根据时间/日期排序,那么只需使用 shuffle=False

from sklearn.model_selection import train_test_split

#target_attribute = df['column_name'] 
#You should drop target column before, you put it into train_test_split. 
#df = df.drop(columns = ['column_name'], axis = 1)

trainingSet, testSet = train_test_split(df,
                                        #target_attribute, 
                                        test_size=0.2,
                                        random_state=42,
                                        #stratify=y,
                                        shuffle=False)

【讨论】:

    【解决方案2】:

    this SO post 中所述,您可以将其与np.split 分开:

    import numpy as np
    df = df.sort_values('date') 
    data = df.values
    train_set, test_set= np.split(data, [int(.9 * len(data))])
    

    【讨论】:

      猜你喜欢
      • 2019-05-01
      • 1970-01-01
      • 2019-06-30
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2021-02-27
      • 2020-11-11
      相关资源
      最近更新 更多