将列表列转换为python

2024-03-28 21:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,假设我有一列清单

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

如何将其转换为python集?你知道吗

例如

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

我试过做set(df['column1']),但结果是出错了


Tags: dfprintsetcolumn1pythonset
2条回答

又短又甜:

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

其想法是首先将列表列扁平化为单个iterable。对于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'}

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

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

输出:

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

相关问题 更多 >