Skip to content Skip to sidebar Skip to footer

How To Convert List Into Set In Pandas?

I have a dataframe as below: 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,

Solution 1:

You should use apply method of DataFrame API:

df['uids'] = df.apply(lambda row: set(row['uids']), axis=1)

or

df = df['uids'].apply(set) # great thanks to EdChum

You can find more information about apply method here.

Examples of use

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)

Output:

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

Or:

>>>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])

Post a Comment for "How To Convert List Into Set In Pandas?"