How to convert list into set in pandas?

后端 未结 1 1250
北恋
北恋 2020-12-16 02:58

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         


        
相关标签:
1条回答
  • 2020-12-16 03:13

    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
    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])
    
    0 讨论(0)
提交回复
热议问题