[英]How to choose the rows where the first occurrence of a value happens with groupby in pandas and also the first of the consequent occurrences
[英]pandas groupby, keep only rows with first occurrence
對於我希望實現的目標,這是一個緩慢的解決方案。 問題是性能。 沒有用戶定義的功能,是否有更“寬泛”的方法來實現這一目標? 目標是僅保留每個組中出現的第一個時間戳的所有行。
def get_first_id_time(df):
first_time = df['datetime'][0]
df = df.loc[df['datetime']==first_time]
return df
data = data.groupby('id').apply(get_first_id_time)
編輯:注意,每個組有許多行datetime = first_time。
你能獲得min
日期時間並merge
嗎?
min_datetime = data.groupby('id')['datetime'].min().reset_index()
data = data.merge(min_datetime, how='inner', on='id')
編輯:
由於有許多行具有相同的first_datetime
,因此只需merge
datetime
和id
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.