Pandas Dataframe 在列表列中删除重复项?

luk*_*rku 2 python numpy dataframe pandas

我正在尝试删除 columnsa和中的重复项c

        a      b    c
0  [1, 0]      1    ab
1  [0, 0]      2    bc
2  [1, 0]      3    ab
Run Code Online (Sandbox Code Playgroud)

结果输出:

        a      b    c
0  [1, 0]      1    ab
1  [0, 0]      2    bc
Run Code Online (Sandbox Code Playgroud)

我尝试过的:没有列出a列。df.drop_duplicates(['a','c'])作品。

没有c列是 str。pd.DataFrame(np.unique(df), columns=df.columns)适用于删除重复列表。

如果其中一列是列表和其他字符串,如何继续。

小智 5

方法一

列表在 pandas 中不可散列,但您可以使用元组。

df['d'] = df['a'].apply(lambda x : tuple(x) if type(x) is list else x)

          a  b   c       d
0    [1, 0]  1  ab  (1, 0)
1    [0, 0]  2  bc  (0, 0)
2    [1, 0]  3  ab  (1, 0)

Run Code Online (Sandbox Code Playgroud)

然后

df = df.drop_duplicates(subset=['c', 'd'])
Run Code Online (Sandbox Code Playgroud)

结果 :

         a  b   c       d
0    [1, 0]  1  ab  (1, 0)
1    [0, 0]  2  bc  (0, 0)

Run Code Online (Sandbox Code Playgroud)

方法二

您可以将包含列表的列转换为 str。

df['a'] = df['a'].astype(str)
df = df.drop_duplicates(subset=['a', 'c'])
Run Code Online (Sandbox Code Playgroud)

输出

    a      b    c
0  [1, 0]      1    ab
1  [0, 0]      2    bc
Run Code Online (Sandbox Code Playgroud)