How to convert list to set in pandas?

I have a dataframe as shown 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, 10, 11, 12, 13]

When I use setto convert it to set it to fail:

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

How do I convert listto setin place?

+4
source share
1 answer

You should use the apply API DataFrame method:

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 on the application method here .

Examples of using

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
0    set([1, 2, 3, 4, 5])
1          set([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])
+2
source

Source: https://habr.com/ru/post/1611602/


All Articles