0

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.

2
  • Why don't you want a for loop? Commented Oct 13, 2021 at 13:48
  • it takes very long main problem with that are the multiple calls to .iloc to assign the values Commented Oct 13, 2021 at 13:50

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

man you are a genius! thanks this works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.