Python数据框:根据某些条件删除重复项

时间:2019-12-03 04:00:35

标签: python pandas dataframe drop-duplicates

具有重复的商店ID的数据框,其中一些商店ID出现两次,而某些三次发生:
我只想根据分配给其区域的最短商店距离来保留唯一的商店ID。

    Area  Shop Name  Shop Distance  Shop ID   

0   AAA   Ly         86             5d87790c46a77300
1   AAA   Hi         230            5ce5522012138400
2   BBB   Hi         780            5ce5522012138400
3   CCC   Ly         450            5d87790c46a77300
...
91  MMM   Ju         43             4f76d0c0e4b01af7
92  MMM   Hi         1150           5ce5522012138400
...

使用pandas drop_duplicates删除重复的行,但条件基于第一个/最后一个出现的Shop ID,该ID不允许我按距离排序:

shops_df = shops_df.drop_duplicates(subset='Shop ID', keep= 'first')

我也尝试按商店ID分组,然后进行排序,但是排序返回错误:重复

bbtshops_new['C'] = bbtshops_new.groupby('Shop ID')['Shop ID'].cumcount()
bbtshops_new.sort_values(by=['C'], axis=1)

到目前为止,我一直尝试着完成这一阶段:

# filter all the duplicates into a new df
df_toclean = shops_df[shops_df['Shop ID'].duplicated(keep= False)]

# create a mask for all unique Shop ID
mask = df_toclean['Shop ID'].value_counts()

# create a mask for the Shop ID that occurred 2 times
shop_2 = mask[mask==2].index

# create a mask for the Shop ID that occurred 3 times
shop_3 = mask[mask==3].index

# create a mask for the Shops that are under radius 750 
dist_1 = df_toclean['Shop Distance']<=750

# returns results for all the Shop IDs that appeared twice and under radius 750
bbtshops_2 = df_toclean[dist_1 & df_toclean['Shop ID'].isin(shop_2)]

* if i use df_toclean['Shop Distance'].min() instead of dist_1 it returns 0 results

我认为我正在做很长的路要走,但仍然没有弄清楚如何删除重复项,有人知道如何用更短的方法解决吗?我是python的新手,感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

尝试首先根据距离对数据框进行排序,然后删除重复的商店。

df = shops_df.sort_values('Distance')
df = df[~df['Shop ID'].duplicated()]  # The tilda (~) inverts the boolean mask.

或者就像一个链接表达式(来自@chmielcode的注释)。

df = (
    shops_df
    .sort_values('Distance')
    .drop_duplicates(subset='Shop ID', keep= 'first')
    .reset_index(drop=True)  # Optional.
)

答案 1 :(得分:0)

您可以使用idxmin:

df.loc[df.groupby('Area')['Shop Distance'].idxmin()]

  Area Shop Name  Shop  Distance              Shop ID
0  AAA        Ly              86     5d87790c46a77300
2  BBB        Hi             780     5ce5522012138400
3  CCC        Ly             450     5d87790c46a77300
4  MMM        Ju              43     4f76d0c0e4b01af7