我们有以下代码:
import pandas as pd
table = {"Col 1":{"0":"Row 1","1":"Row 2","2":"Row 3","3":"Row 4","4":"Row 5","5":"Row 6","6":"Row 7","7":"Row 8","8":"Row 9","9":"Row 10"},"Col 2":{"0":0,"1":1,"2":0,"3":0,"4":1,"5":0,"6":0,"7":1,"8":1,"9":1}}
tabledf = pd.DataFrame(table)
tabledf["Col 3"] = "??"
哪个返回:
Col 1 Col 2 Col 3
0 Row 1 0 ??
1 Row 2 1 ??
2 Row 3 0 ??
3 Row 4 0 ??
4 Row 5 1 ??
5 Row 6 0 ??
6 Row 7 0 ??
7 Row 8 1 ??
8 Row 9 1 ??
9 Row 10 1 ??
在第3列中,我们希望在前2行中显示1,在第2行中显示1(在下面显示0).
这是所需的输出:
Col 3
0
1
0
0
1
0
0
0
0
0
我们该怎么做呢?
解决方法:
您的逻辑可以分为两个条件,必须同时满足两个条件:
> Col 2等于1.
> Col 2的计数等于1小于或等于2.
然后,您可以矢量化方式应用此方法,最后一步将其转换为int:
df['Col 3'] = (df['Col 2'].eq(1) & df['Col 2'].eq(1).cumsum().le(3)).astype(int)
print(df)
Col 1 Col 2 Col 3
0 Row 1 0 0
1 Row 2 1 1
2 Row 3 0 0
3 Row 4 0 0
4 Row 5 1 1
5 Row 6 0 0
6 Row 7 0 0
7 Row 8 1 0
8 Row 9 1 0
9 Row 10 1 0