Python 基于两列值定义目标
我是python新手,在解决以下问题时遇到了一些问题 我有以下数据帧:Python 基于两列值定义目标,python,pandas,Python,Pandas,我是python新手,在解决以下问题时遇到了一些问题 我有以下数据帧: SoldDate CountSoldperMonth 2019-06-01 20 5 10 12 33 16 50 2
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
我需要添加一个目标列,以便对于特定SoldDate的“CountSoldperMonth”中的前5个值,目标值应为1或0。如果特定“SoldDate”的“CountSoldperMonth”中的行数小于5,则在目标中只有计数最高的行将标记为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
如何做到这一点?在您的案例中,使用groupby和规则链以及apply if…else
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
如果特定“SoldDate”的“CountSoldperMonth”中的行数小于5,则在目标中只有最高计数将标记为1,其余为0。这将为特定SoldDate的“CountSoldperMonth”中的最高值指定1作为目标,其他为0。