![](/img/trans.png)
[英]Check if a vaue in a dataframe exists in another dataframe with a condition
[英]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
df['Segment'] = df['ID'].isin(special).astype(int)
我們也可以使用Series.view
:
df['Segment'] = df['ID'].isin(special).view('uint8')
df['Segment'] = np.where(df['ID'].isin(special),1 ,0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.