簡體   English   中英

在熊貓數據框中保留第一行連續的特定值?

[英]Keep the first rows of continuous specific values in a pandas data frame?

我有一個這樣的數據框,

df
col1    col2
 1       A
 2       A
 3       A
 4       A
 5       A
 6       A
 7       B
 8       B
 9       A
 10      A
 11      A
 12      A
 13      B
 14      A
 15      B
 16      A
 17      A
 18      A

現在,如果兩個 B 之間有連續的 B 或只有一行,則顯示這些 B 的起始行。

所以最終輸出看起來像,

 col1    col2
 7       B
 13      B

我可以通過比較行值來使用 for 循環來做到這一點,但執行時間會很長。 我正在尋找任何熊貓快捷方式或任何其他方法來最有效地做到這一點。

您可以先將非B值替換為缺失值,然后通過限制1向前填充它們 - 所以最后 2 B創建一個組並最后獲取B組的第一個值:

m = df['col2'].where(df['col2'].eq('B')).ffill(limit=1).eq('B')
df = df[ m.ne(m.shift()) & m]
print (df)
    col1 col2
6      7    B
12    13    B

您可以使用移位和向量邏輯:

a = df['col2']
mask = (a.shift(1) != a) & ((a.shift(-1) == a) | (a.shift(-2) == a)) & (a == 'B')
df = df[mask]
cols = []
for i in range(len(df)):
    if i!=0:
        if df['col2'][i]==B and df['col2'][i-1]!=B:
            if i>=2 and df['col2'][i-1]!=B:
                cols.append(df['col1'][i])

print(df[df['col1'].isin(cols)])

輸出:

col1    col2
 7       B
 13      B

找到 B 沒有它的 i-1 和 i-2 行沒有 B 的索引,並從檢索到的索引的數據框中檢索行。

暫無
暫無

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

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