【问题标题】:Select rows based on dynamic criteria根据动态条件选择行
【发布时间】:2019-12-30 18:23:54
【问题描述】:

目前我正在研究这种数据集:

         date   income    account  flag  day  month  year
0  2018-04-13   470.57  1000 0002     8   13      4  2018  
1  2018-04-14   375.54  1000 0002     8   14      4  2018  
2  2018-05-15   375.54  1000 0002     8   15      5  2018  
3  2018-05-16   229.04  1000 0002     7   16      5  2018  
4  2018-06-17   216.62  1000 0002     7   17      6  2018  
5  2018-06-18   161.61  1000 0002     6   18      6  2018  
6  2018-04-19   131.87  0000 0001     6   19      4  2018  
7  2018-04-20   100.57  0000 0001     6   20      4  2018  
8  2018-08-21   100.57  0000 0001     6   21      8  2018  
9  2018-08-22    50.57  0000 0001     5   22      8  2018  

我正在研究一个决策树回归模型,将 RandomForest 与 ExtraTrees 进行比较并调整它的一些超参数。我目前正在尝试做的是拆分数据集,以便为每个唯一值 account 保留具有列 month 最大值的行(如果它更容易,也可以将其设置为索引)为test_set 和其他作为 train_set。基本上,这意味着将使用所有可用的历史数据进行回归,但属于最后一个可用月份的数据将用于验证 mse。

我知道如何根据 df[df['month'] < 12] 等静态条件过滤数据框,但在这种情况下,我需要为每个不同的 account 值保留所有属于最大月份的行。

从以前的数据集中我应该能够得到类似:df_test =

         date   income    account  flag  day  month  year 
4  2018-06-17   216.62  1000 0002     7   17      6  2018  
5  2018-06-18   161.61  1000 0002     6   18      6  2018   
8  2018-08-21   100.57  0000 0001     6   21      8  2018  
9  2018-08-22    50.57  0000 0001     5   22      8  2018  

还有df_train =

         date   income    account  flag  day  month  year
0  2018-04-13   470.57  1000 0002     8   13      4  2018  
1  2018-04-14   375.54  1000 0002     8   14      4  2018  
2  2018-05-15   375.54  1000 0002     8   15      5  2018  
3  2018-05-16   229.04  1000 0002     7   16      5  2018  
6  2018-04-19   131.87  0000 0001     6   19      4  2018  
7  2018-04-20   100.57  0000 0001     6   20      4  2018 

例如,对于df['account'] = 1000 0002,我可以使用第 4 个月和第 5 个月进行预测,并使用第 6 个月进行验证。谢谢!

【问题讨论】:

    标签: python pandas filtering


    【解决方案1】:

    您可以使用transform

    test=df[df.month==df.groupby('account').month.transform('max')].copy()
    train=df.drop(test.index)
    test
    Out[643]: 
             date  income   account  flag  day  month  year
    4  2018-06-17  216.62  10000002     7   17      6  2018
    5  2018-06-18  161.61  10000002     6   18      6  2018
    8  2018-08-21  100.57         1     6   21      8  2018
    9  2018-08-22   50.57         1     5   22      8  2018
    

    【讨论】:

    • 这似乎是解决方案!我会在一分钟内尝试它,如果它有效,我会投票赞成:) 谢谢!
    猜你喜欢
    • 2020-01-24
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2014-02-21
    相关资源
    最近更新 更多