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.
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.
CodePudding user response:
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