user1828513
user1828513

Reputation: 397

python dataframe how to convert set column to list

I tried to convert a set column to list in python dataframe, but failed. Not sure what's best way to do so. Thanks.

Here is the example: I tried to create a 'c' column which convert 'b' set column to list. but 'c' is still set.

data = [{'a': [1,2,3], 'b':{11,22,33}},{'a':[2,3,4],'b':{111,222}}]
tdf = pd.DataFrame(data)
tdf['c'] = list(tdf['b'])
tdf
           a             b             c
0  [1, 2, 3]  {33, 11, 22}  {33, 11, 22}
1  [2, 3, 4]    {222, 111}    {222, 111}

Upvotes: 5

Views: 5170

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could do:

import pandas as pd

data = [{'a': [1,2,3], 'b':{11,22,33}},{'a':[2,3,4],'b':{111,222}}]
tdf = pd.DataFrame(data)

tdf['c'] = [list(e) for e in tdf.b]

print(tdf)

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71560

Use apply:

tdf['c'] = tdf['b'].apply(list)

Because using list is doing to whole column not one by one.

Or do:

tdf['c'] = tdf['b'].map(list)

Upvotes: 3

Related Questions