首页 > 解决方案 > 检查两个索引内列中数据框中的重复值

问题描述

我有一个数据框,如 excel 文件中所示

在此处输入图像描述

我想根据 id 查找重复值,例如nn_id列中ID 0 and ID 1的值不相同,因此我们进一步检查nn_id列中 的值是否相同,因此如果值相同,它们会打印 nn_id 列中的切片-0010-EDSR_x2_Xslice-0010-EDSR_x2_Y 所以输出将是字典的形式进一步检查哪些值不相同,所以什么也不做。366 393ID 2 and ID 3595 595{595:[(492,260),(491,248)]}ID 4 and ID 5458 486

如果它令人困惑,我很抱歉,但我想检查两个 ID 的nn_id值是否相同,然后制作一个相邻列值的字典。

标签: pythonpandasdataframeindexingduplicates

解决方案


这是否实现了您的目标?可能有更优雅的方法来实现相同的目标。我假设你DataFrame df的桌子上有一个。

df_shift = df.shift(1)    # shift database with 1 row
same_idx = df['nn_id'] == df_shift['nn_id']

# get column positions for columns of interest
col1_pos = df.columns.get_loc('slice-0010-EDSR_x2_X ')
col2_pos = df.columns.get_loc('slice-0010-EDSR_x2_Y')
nn_idx_pos = df.columns.get_loc('nn_id')
my_dict = {}   # define empty dict to store your results.
for i in np.where(same_idx)[0]:   # for each row where the nn_idx value is the same
    # define the value that you're after
    my_value = [(df.iloc[i-1, col1_pos], df.iloc[i-1, col2_pos]),
                (df.iloc[i, col1_pos], df.iloc[i, col2_pos])]
    # and add element to dictionary
    my_dict[df.iloc[i, nn_idx_pos]] = my_value

推荐阅读