簡體   English   中英

刪除 pandas 中的所有行,直到找到特定字符串然后停止刪除

[英]Drop ALL rows in pandas until a specific string is found then stop dropping

我有一個數據框,我想刪除每一行,直到找到特定的字符串。

我嘗試了幾件事,但似乎沒有任何效果。 這是我嘗試過的:

df[((df.Plate != 'Group Summaries'))]
df.loc[: df[(df['Plate:'] == 'Group Summaries')].index[0], :]
df[(df['Plate:'] == "Group Summaries").idxmax():]

為什么不找到出現這種情況的第一個索引,然后刪除所有前面的行?

import pandas as pd

# Data
df = pd.DataFrame(
    {"Plate": ["a", "b", "a", "c", "a", "c", "c"]})

# First index where values is c
idx = df.index[df["Plate"].eq("c")].min()

# Drop previous rows
df = df[idx:]

您可以使用:

df[df['Plate'].eq('Group Summaries').cummax()]

這個怎么運作:

  • 將“板塊”列中帶有“組摘要”的行標記為真
  • 使用cummax將 True 轉發到所有下一行
  • 使用布爾索引來選擇行

暫無
暫無

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

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