将熊猫列表转换为虚拟变量

问题描述:

我有一个熊猫数据框,其中包含我想要转换为虚拟变量的变量列表。基本上,我想转换:将熊猫列表转换为虚拟变量

enter image description here

这样:

enter image description here

df = pd.DataFrame({0: [['hello', 'motto'], ['motto', 'mania']]}) 
print(df) 

       0 
0 [hello, motto] 
1 [motto, mania] 

使用str.join其次str.get_dummies

df[0].str.join('|').str.get_dummies() 

    hello mania motto 
0  1  0  1 
1  0  1  1 
+0

谢谢!当我被允许时会接受答案! – laila

+0

@laila欢迎您。 – piRSquared

下面是一个存储器中保存的解决方案这是会使用稀疏矩阵和Pandas.SparseSeries:

​​

结果:

In [81]: df 
Out[81]: 
    hello mania motto 
0  1  0  1 
1  0  1  1 

In [82]: df.memory_usage() 
Out[82]: 
Index 80 
hello  8 # notice memory usage: # of ones multiplied by 8 bytes (int64) 
mania  8 
motto 16 
dtype: int64