Sunny
Sunny

Reputation: 302

How to expand pandas column containing values in arrays to multiple columns?

I have a data frame with column named 'gear' which contains lists of values... what i want to do now is to move each element in every list to the corresponding column. enter image description here

is there a way to do this without a need for a for loop? for example in the first row the value 'Hengerfeste' in the list should be moved to 'Hengerfeste' column and so on for each element in the list.

Upvotes: 0

Views: 740

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

Try explode, then groupby().value_counts():

#sample data
df = pd.DataFrame({'col':[['a','b','c'], ['a','c','x'],[],['b','x','y']]})


(df['your_list_col'].explode()
   .groupby(level=0).value_counts()
   .unstack(fill_value=0)
   .reindex(df.index, fill_value=0)
)

Output:

col  a  b  c  x  y
0    1  1  1  0  0
1    1  0  1  1  0
2    0  0  0  0  0
3    0  1  0  1  1

Upvotes: 2

Related Questions