如何在pandas中将列表转换为集合?

17

我有一个如下的数据框:

           date                     uids
0  2018-11-23  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
1  2018-11-24  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

当我使用set把它转换为集合时,它失败了:

df['uids'] = set(df['uids'])  # IT FAILS!

如何将list就地转换为set

2个回答

18

您应该使用 DataFrame API 的 apply 方法:

df['uids'] = df.apply(lambda row: set(row['uids']), axis=1)
或者
df = df['uids'].apply(set) # great thanks to EdChum

您可以在此处找到更多关于apply方法的信息。

使用示例

df = pd.DataFrame({'A': [[1,2,3,4,5,1,1,1], [2,3,4,2,2,2,3,3]]})
df = df['A'].apply(set)

输出:

>>> df
0    set([1, 2, 3, 4, 5])
1          set([2, 3, 4])
Name: A, dtype: object

或者:

>>> df = pd.DataFrame({'A': [[1,2,3,4,5,1,1,1], [2,3,4,2,2,2,3,3]]})
>>> df['A'] = df.apply(lambda row: set(row['A']), axis=1)
>>> df
                      A
0  set([1, 2, 3, 4, 5])
1        set([2, 3, 4])

@EdChum 的 lambda 解决方案很棒,但也许你的解决方案没有就地更新?! - Alireza
1
@AlirezaHos 你在说什么?你只需要执行 df['usids'] = df['uids'].apply(set)apply 没有 inplace 参数,无论如何你都必须分配结果。 - EdChum
@EdChum 我只是使用了你说的那部分。现在它可以工作了。谢谢你!+1 - Alireza
@EdChum,当我的列表包含30,000个UID时,应用函数需要很长时间(19秒)。难道没有更好的方法来提高性能吗? - Alireza
2
“apply”只是一个“for”循环,所以这会很慢。不幸的是,没有“toset”方法。 - EdChum

1
对于想要了解在Pandas中将列表转换为集合的最快方法的任何人:
方法1:
df['uids'] = df.apply(lambda row: set(row['uids']), axis=1)

方法二:
df['uids'] = df['uids'].apply(set)

方法三:
df['uids'] = df['uids'].map(set)

我用repeat(50, 5)对有4000行的DF进行了时间测试:

Method 1 - mean:  0.13299, min:  0.12723
Method 2 - mean:  0.01319, min:  0.01207
Method 3 - mean:  0.01261, min:  0.01164

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接