簡體   English   中英

檢查數據框中的 ID 是否存在於另一個數據框中的最快方法

[英]Fastest way to check if an ID in your dataframe exists in another dataframe

我有大熊貓數據框(大約一百萬行)和一個 id-s 列表(數組長度為 100,000)。 對於 df1 中的每個 id,我必須檢查該 id 是否在我的列表中(稱為special )並相應地對其進行標記:

df['Segment'] = df['ID'].apply(lambda x: 1 if x in special else np.nan)

問題是這非常慢,因為百萬 id-s lambda 表達式檢查該 id 是否在 100,000 個條目的列表中。 有沒有更快的方法來實現這一點?

我建議你看看When should I ever want to use apply

使用Series.isinSeries.astype

 df['Segment'] = df['ID'].isin(special).astype(int)

我們也可以使用Series.view

df['Segment'] = df['ID'].isin(special).view('uint8')

numpy.where

df['Segment'] = np.where(df['ID'].isin(special),1 ,0)

暫無
暫無

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

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