我正在嘗試執行以下操作:“# drop all rows where tag == train_loop and start is NaN”。
這是我目前的嘗試(感謝副駕駛):
# 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)]
它運作良好,但我想知道是否有一種不那么冗長的方式。
uj5u.com熱心網友回復:
usingapply實際上是一種非常糟糕的方法,因為它回圈遍歷每一行,呼叫您在 python 中定義的函式。相反,使用可以在整個資料幀上呼叫的向量化函式,這些函式呼叫引擎蓋下用 C 撰寫的優化/向量化版本。
df = df[~((df["tag"] == "train_loop") & df["start"].isnull())]
如果您的資料很大(>~100k 行),那么更快的是使用 pandasquery方法,您可以將兩個條件寫在一個中:
df = df.query(
'~((tag == "train_loop") and (start != start))'
)
這利用了 NaN 永遠不等于任何東西的事實,包括它們自己,因此我們可以使用簡單的邏輯運算子來查找 NaNS(.isnull()在編譯查詢迷你語言中不可用)。為了使查詢方法更快,您需要numexpr安裝,它將在呼叫資料之前即時編譯您的查詢。
有關更多資訊和示例,請參閱有關增強性能的檔案。
uj5u.com熱心網友回復:
你可以做
df = df.loc[~(df['tag'].eq('train_loop') & df['start'].isna())]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532953.html
標籤:Python熊猫
