Python-检查值是否位于前n行中
我们有以下代码:Python-检查值是否位于前n行中,python,pandas,Python,Pandas,我们有以下代码: 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 =
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
我们如何做到这一点?您的逻辑可以分为两个标准,这两个标准都必须满足:
tabledf['Col 3'] = 0
tabledf.loc[tabledf['Col 2'].loc[lambda x: x==1][:2].index, 'Col 3']=1
print(tabledf)
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
col2
等于1Col 2
等于1的计数小于或等于2int
:
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
谢谢不在列行中定义它?