apply(set) to two columns in a pandas dataframe

Viewed 5801

I have three columns in a dataframe. I would like to make the second and third column have sets as opposed to lists. Using df['column_name_2 and column_name_3'].apply(set) results in an error because, as I understand it, this function will only take 1 argument. However splitting them into two separate functions, completely eliminates column three.

This is what I have:

    column_1     column_2     column_3
       1         [lk, 18m]    [kjaf]

This is what I want:

    column_1     column_2     column_3
       1         {lk, 18m}    {kjaf}
1 Answers

I think need define columns in nested lists and then applymap with sets:

df[['column_2', 'column_3']] = df[['column_2', 'column_3']].applymap(set)

Or use loop:

cols = ['column_2', 'column_3']
for c in cols:
    df[c] = df[c].apply(set)

Sample:

df = pd.DataFrame({'column_1': [1, 1], 
                   'column_2': [['lk', '18m'], ['lk', 'r']],
                   'column_3': [['kjaf'], ['ddd']]})

print (df)
   column_1   column_2 column_3
0         1  [lk, 18m]   [kjaf]
1         1    [lk, r]    [ddd]

df[['column_2', 'column_3']] = df[['column_2', 'column_3']].applymap(set)
print (df)
   column_1   column_2 column_3
0         1  {18m, lk}   {kjaf}
1         1    {r, lk}    {ddd}
Related