首页 > 解决方案 > 如何从两个不同的列表中删除重复项,一个只包含 int,另一个包含混合的 int 和 str?

问题描述

我有一个带有一些列的 df。列表中的条目应根据其中两列进行过滤/删除其重复项:其中一列仅包含数字,而另一列包含混合字符串(字母 + 数字)和数字。

我想做的是:将第一列中的数字与:

  1. 第二列中每个字符串末尾的数字(总是最后 X 个字符)

  2. 第二列中的数字,然后删除重复的条目。

条目要么在其中一列中有信息,要么有一个空字符串。

例子:

Col 1 | Col 2 | Col 3

ABC.  | 12345 | ""

DEF.  | ""    | DEF12345

GHI.  | ""    | 12345

如您所见,我们有 3 个不同的条目。我想根据第 2 列和第 3 列进行过滤。

提前非常感谢!

标签: pythonlist

解决方案


假设您的 DataFrame 是:

df = pd.DataFrame(
    {
        'Col 1':['ABC', 'DEF', 'GHI'],
        'Col 2':[12345, '', ''],
        'Col 3':['','DEF12345', 12345]
    }
)

print(df)

  Col 1  Col 2     Col 3
0   ABC  12345          
1   DEF         DEF12345
2   GHI            12345

您必须构建一个自定义函数来正确解析和转换值,然后其应用于您想要的列。

鉴于您的问题不够清晰,在这里我只能做一个虚拟示例,您必须对其进行修改以使其适用于您的实际情况。

def str_to_int(val):
    if type(val) is int:
        return val
    elif type(val) is str:
        if val == '':
            return 0 #you have to choose how to deal with this
        else:
            return int(val[3:]) #assuming you have always 3 letters before the number

df['Col 2'] = df['Col 2'].apply(str_to_int)
df['Col 3'] = df['Col 3'].apply(str_to_int)

print(df)

  Col 1  Col 2  Col 3
0   ABC  12345      0
1   DEF      0  12345
2   GHI      0  12345

现在您可以轻松找到重复项,因为所有条目都是数字。

#Make a new column that keeps only the non 0 integers
def exclude_zeros(row):
    return row['Col 2'] or row['Col 3']

df['Col 4'] = df.apply(exclude_zeros, axis=1)

#Remove the duplicates and keep only the relevant data
df = df.drop_duplicates(subset='Col 4', keep='first')[['Col 1', 'Col 4']]

print(df)

Col 1  Col 4
0   ABC  12345

推荐阅读