我有一个很大的数据框(超过100列,几十万行),其中许多行包含重复数据。我试图删除重复的行,将具有最大值的行保留在另一列中。
从本质上讲,我是根据时间段将数据分类到各个bin中,因此在整个周期中,由于大多数实体都存在于所有时间段中,因此人们会期望找到很多重复项。但是,不允许的是同一实体在给定时间段内出现多次。
我尝试了python pandas中的方法:删除A列的重复项,并在数据的子集上将B列中具有最大值的行保留在该数据的子集上,并计划与原始数据帧df重组。
示例数据子集:
unique_id period_id liq
index
19 CAN00CE0 199001 0.017610
1903 **USA07WG0** 199001 1.726374
12404 **USA07WG0** 199001 0.090525
13330 USA08DE0 199001 1.397143
14090 USA04U80 199001 2.000716
12404 USA07WG0 199002 0.090525
13330 USA08DE0 199002 1.397143
14090 USA04U80 199002 2.000716
在上面的示例中,我想保留第一个实例(因为liq较高,为1.72),而丢弃第二个实例(liq较低,为0.09)。请注意,在给定的period_id中可以有两个以上的重复项。
我试过了,但是对我来说很慢(超过5分钟后我停止了):
def h(x):
x = x.dropna() #idmax fails on nas, and happy to throw out where liq is na.
return x.ix[x.liq.idmax()]
df.groupby([‘holt_unique_id’, ‘period_id’], group_keys = False).apply(lambda x: h(x))
我最终做了下面的工作,它比较冗长和丑陋,只抛出了一个重复项,但全部都扔掉了,但这也很慢!考虑到其他类似复杂性操作的速度,我想在这里寻求更好的解决方案。
所以我的要求确实是要修复上面的代码,以便快速,下面给出了指导,如果按照下面的观点,也许我也可以根据索引而不是reset_index / set_index丢弃重复项我采用的方法:
def do_remove_duplicates(df):
sub_df = df[['period_id', 'unique_id']]
grp = sub_df.groupby(['period_id', 'unique_id'], as_index = False)
cln = grp.apply(lambda x: x.drop_duplicates(cols = 'unique_id')) #apply drop_duplicates. This line is the slow bit!
cln = cln.reset_index() #remove the index stuff that has been added
del(cln['level_0']) #remove the index stuff that has been added
cln.set_index('level_1', inplace = True) #set the index back to the original (same as df).
df_cln = cln.join(df, how = 'left', rsuffix = '_right') # join the cleaned dataframe with the original, discarding the duplicate rows using a left join.
return df_cln
怎么样:
由于它已向量化,因此应该更快。
In [11]: g = df.groupby(["unique_id", "period_id"], as_index=False)
In [12]: g.transform("max")
Out[12]:
liq
index
19 0.017610
1903 1.726374
12404 1.726374
13330 1.397143
14090 2.000716
12404 0.090525
13330 1.397143
14090 2.000716
In [13]: df.update(g.transform("max"))
In [14]: g.nth(0)
Out[14]:
unique_id period_id liq
index
19 CAN00CE0 199001 0.017610
1903 **USA07WG0** 199001 1.726374
13330 USA08DE0 199001 1.397143
14090 USA04U80 199001 2.000716
12404 USA07WG0 199002 0.090525
13330 USA08DE0 199002 1.397143
14090 USA04U80 199002 2.000716
注意:我想在这里首先或最后使用groupby,但是我认为存在一个错误,它们会丢弃您的旧索引,我不认为它们应该...但是,这是可行的。
另一种方法是先切出不等于liq max的那些:
(df[df["liq"] == g["liq"].transform("max")] # keep only max liq rows
.groupby(["unique_id", "period_id"])
.nth(0)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句