Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-检查值是否位于前n行中_Python_Pandas - Fatal编程技术网

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
    等于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
    

    谢谢不在列行中定义它?