根据动态条件选择行

时间:2019-08-26 14:33:47

标签: python pandas filtering

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

         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  

我正在研究DecisionTree回归模型,将RandomForest与ExtraTrees进行比较,并调整其一些超参数。我目前正在尝试对数据集进行拆分,以保留每个唯一值month的列account的最大值的行(如果设置为更简单的方法)作为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个月进行验证。谢谢!

1 个答案:

答案 0 :(得分:5)

您可以使用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