簡體   English   中英

Python Pandas - 檢查值是否在前n行中

[英]Python Pandas - Check if a value is in the top n rows

我們有這個代碼:

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列中,我們要在頂部/前兩行中顯示1,在第2列中有1(以下為0)。 這是所需的輸出:

Col 3
0
1
0
0
1
0
0
0
0
0

我們該怎么做呢?

您的邏輯可以分為兩個條件,這兩個條件都必須滿足:

  1. Col 2等於1。
  2. 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
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM