簡體   English   中英

如果第 1 列 = 特定值且第 2 列 = NaN,如何刪除 pandas 中的行?

[英]How to drop row in pandas if column1 = certain value and column 2 = NaN?

我正在嘗試執行以下操作:“# 刪除 tag == train_loop 且 start 為 NaN 的所有行”。

這是我目前的嘗試(感謝 Copilot):

# drop all rows where tag == train_loop and start is NaN
# apply filter function to each row
# return True if row should be dropped
def filter_fn(row):
    return row["tag"] == "train_loop" and pd.isna(row["start"]):

old_len = len(df)
df = df[~df.apply(filter_fn, axis=1)]

它運作良好,但我想知道是否有更簡潔的方法。

實際上,使用apply是一種非常糟糕的方法,因為它會遍歷每一行,調用您在 python 中定義的 function。相反,請使用可以在整個 dataframe 上調用的矢量化函數,它會調用 C 中編寫的優化/矢量化版本在引擎蓋下。

df = df[~((df["tag"] == "train_loop") & df["start"].isnull())]

如果您的數據很大(>~100k 行),那么使用 pandas query方法會更快,您可以將兩個條件寫在一個查詢方法中:

df = df.query(
    '~((tag == "train_loop") and (start != start))'
)

這利用了 NaN 永遠不等於任何東西(包括它們自身)這一事實,因此我們可以使用簡單的邏輯運算符來查找 NaNS( .isnull()在編譯查詢迷你語言中不可用)。 為了使查詢方法更快,您需要安裝numexpr ,它將在調用數據之前動態編譯您的查詢。

有關更多信息和示例,請參閱有關增強性能的文檔。

你可以做

df = df.loc[~(df['tag'].eq('train_loop') & df['start'].isna())]

暫無
暫無

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

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