标识数据帧中具有值的行,该值存在于另一个数据帧的列表列中并且是重复的



我有一个pandas数据帧,大约有2.5M行。这些行中的每一行都有一个位置标识符,大约有2000个位置。我想删除任何具有相同属性且距离另一个位置X英里以内的行的重复项,并保留第一个值。

在最初过滤重复值后,数据帧看起来类似于以下内容:

index  location_id    attr1    attr2

1         1            A        Z
2         1            B        Y
3         2            A        Z
4         3            B        Y
5         5            A        Z
6         5            B        Y

我有另一个数据帧,它包含位置id和考虑的位置列表";附近的";看起来像这样:


location_id   locations

1           [3,5]
2            []
3           [1,5]
5           [1,3]

如何在不过滤第2行和第3行的情况下,使用附近的位置数据帧从数据帧中过滤出第4行、第5行和第6行?

编辑:预期输出如下:

index  location_id    attr1    attr2

1         1            A        Z
2         1            B        Y
3         2            A        Z

对于将来试图解决类似问题的任何人,我使用以下步骤解决了它。


grouped = duplicate_df.groupby(["attr1", "attr2"])["location_id"].apply(lambda x: x.unqiue())
grouped_df = grouped.to_frame().reset_index()
grouped_df = grouped_df[grouped_df["location_id"].apply(lambda x: len(x) > 1)]
grouped_df.reset_index(drop=True, inplace=True)
grouped_df["LocationList"] = grouped_df["location_id"]
gdf_exploded = grouped_df.explode["location_id"]

#nearly_location_list is the nearby locations data frame mentioned above 
def get_overlap_set(location_id, location_list):
try:
return list(set(location_list).intersection(set(nearly_location_list[nearly_location_list["location_id"] == loaction_id]["locations"].values[0])))+[location_id]
except IndexError:
return [location_id]

gdf_exploded["overlap"] = gdf_exploded.apply(lambda x: get_overlap_set(x["location_id"], x[""]), axis=1)
gdf_exploded["overlap"] = gdf_exploded["overlap"].apply(lambda x: sorted(x))
gdf_exploded.reset_index(drop=True, inplace=True)
gdf_exploded["overlap_string"] = gdf_exploded["overlap"].apply(lambda x: ",".join(list(map(lambda y: str(y), x))))
dedupped_df = gdf_exploded.drop_duplicates(subset=["attr1", "attr2", "overlap_string"])

代码将项目分组,然后使用集合来确定存在重叠的交叉点

最新更新