将列表的熊猫列转换为python集

时间:2019-11-12 05:44:14

标签: python pandas

说我有一个列表的熊猫列,例如

column1
['a', 'b', 'b', 'd', 'e']
['b', 'e', 'g']

如何将其转换为python集?

例如

print(pythonSet)
> {'a', 'b', 'd', 'e', 'g'}

我尝试做set(df['column1']),但这会导致错误

2 个答案:

答案 0 :(得分:5)

又甜又甜:

{*df['column1'].sum()}
# {'a', 'b', 'd', 'e', 'g'}

这个想法是首先将您的列表列展平为一个可迭代的列表。对于python <= 3.5,请使用set(...)而不是解包运算符{*...}


在性能方面更好:

from itertools import chain
{*chain.from_iterable(df['column1'])
# {'a', 'b', 'd', 'e', 'g'}

从性能上也不错-嵌套列表理解(但是chain快一点):

{y for x in df['column1'] for y in x}
# {'a', 'b', 'd', 'e', 'g'}

答案 1 :(得分:1)

如果您拥有pandas 0.25版或更高版本,则可以执行以下操作:

print(set(df["column1"].explode()))

输出:

{'a', 'b', 'd', 'e', 'g'}