如何将包含数组中值的 pandas 列扩展为多列?

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

我有一个数据框,其列名为 'gear',其中包含值列表...我现在要做的是将每个列表中的每个元素移动到相应的列。

有没有不需要 for 循环的方法? 例如,在第一行中,列表中的值 'Hengerfeste' 应该移动到 'Hengerfeste' 列,对于列表中的每个元素依此类推。

尝试 explode,然后 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)
)

输出:

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