根据两个列值定义目标

时间:2019-06-27 17:50:37

标签: python pandas

我是python的新手,我遇到了解决以下问题的问题。

我有以下数据框:

SoldDate       CountSoldperMonth
2019-06-01          20
                    5
                    10
                    12
                    33
                    16
                    50
                    27

2019-05-01          2
                    5
                    11
                    13

2019-04-01          32
                    35
                    39
                    42
                    47
                    55
                    61
                    80

我需要添加一个Target列,以便对于特定SoldDate的“ CountSoldperMonth”中的前5个值,目标应为1,否则为0。如果特定“ SoldDate”的“ CountSoldperMonth”中的行数较少大于5,则在Target中仅将具有最高计数的行标记为1,其余标记为0。结果数据帧应如下所示。

SoldDate       CountSoldperMonth      Target
2019-06-01          20                  1
                    5                   0
                    10                  0
                    12                  0
                    33                  1
                    16                  1
                    50                  1
                    27                  1

2019-05-01          2                   0
                    5                   0
                    11                  0
                    13                  1

2019-04-01          32                  0
                    35                  0
                    39                  0
                    42                  1
                    47                  1
                    55                  1
                    61                  1
                    80                  1

我该怎么做?

1 个答案:

答案 0 :(得分:1)

在您的情况下,将groupby与规则链一起使用apply如果...否则

df.groupby('SoldDate').CountSoldperMonth.\
     apply(lambda x : x==max(x) if len(x)<=5 else x.isin(sorted(x)[-5:])).astype(int)
Out[346]: 
0     1
1     0
2     0
3     0
4     1
5     1
6     1
7     1
8     0
9     0
10    0
11    1
12    0
13    0
14    0
15    1
16    1
17    1
18    1
19    1
Name: CountSoldperMonth, dtype: int32