Python,从列表的DataFrame列中删除重复值

发布于 2025-01-26 13:29:37 字数 321 浏览 1 评论 0原文

我有一个包含列表的DataFrame列,我想从各个列表中删除重复值。

d = {'colA': [['UVB', 'NER', 'GGR', 'NER'], ['KO'], ['ERK1', 'ERK1', 'ERK2'], []]}
df = pd.DataFrame(data=d)

我想从列表中删除重复的“ ner”和“ erk1”。

我尝试过:

df['colA'] = set(tuple(df['colA']))

我收到错误消息: TypeError:不可用的类型:“列表”

I've got a dataframe column containing lists, and I want to remove duplicate values from the individual lists.

d = {'colA': [['UVB', 'NER', 'GGR', 'NER'], ['KO'], ['ERK1', 'ERK1', 'ERK2'], []]}
df = pd.DataFrame(data=d)

I want to remove the duplicate 'NER' and 'ERK1' from the lists.

I've tried:

df['colA'] = set(tuple(df['colA']))

I get the error message:
TypeError: unhashable type: 'list'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南烟 2025-02-02 13:29:37

您可以使用apply() pandas函数的方法从列表中删除重复值,如下所示。

import pandas as pd
d = {'colA': [['UVB', 'NER', 'GGR', 'NER'], ['KO'], ['ERK1', 'ERK1', 'ERK2'], []]}
df = pd.DataFrame(data=d)

df['colA'].apply(lambda x: list(set(x)))

#output
0    [NER, UVB, GGR]
1               [KO]
2       [ERK2, ERK1]
3                 []
Name: colA, dtype: object 

You can remove duplicates values from the list using apply() method of pandas function as follows.

import pandas as pd
d = {'colA': [['UVB', 'NER', 'GGR', 'NER'], ['KO'], ['ERK1', 'ERK1', 'ERK2'], []]}
df = pd.DataFrame(data=d)

df['colA'].apply(lambda x: list(set(x)))

#output
0    [NER, UVB, GGR]
1               [KO]
2       [ERK2, ERK1]
3                 []
Name: colA, dtype: object 
埋情葬爱 2025-02-02 13:29:37

问题是您有列表的元组,这就是为什么设置命令不起作用。您应该在整个元组上迭代。

ans = tuple(df ['cola'])在范围(len(ans))df ['cola']中。

problem is that you have a tuple of lists, thats why set command doesnt work. You should iterate over entire tuple.

ans = tuple(df['colA']) for i in range(len(ans)) df['colA'].iloc[i]=set(ans[i])

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文