Skip to main content
 首页 » 编程设计

python之用于嵌套表的 Pandas Get_dummies

2024年10月24日13三少

我希望利用 pandas get_dummy() 功能来编码一组(相当广泛的)分类变量。但是,数据当前采用嵌套表格格式。这意味着每一行代表另一个变量实例,例如

Instance, Cat_Col 
1, John 
1, Smith 
2, Jane 
3, Joe 

现在我可以生成唯一变量的完整列表,我可以使用它来获取代表所有可能值的 get_dummies。然而,将嵌套表转换为这种新格式的单个实例行给我带来了一些麻烦。

非常感谢任何帮助 谢谢

编辑: 每个实例都应该有一个针对所有 Cat_col 值的虚拟编码结果

想法是结果是像这样的单个特征向量

Instance,Col_John,Col_Smith,Col_Jane,Col_Joe 
1,1,1,0,0 
2,0,0,1,0 
3,0,0,0,1 

我相信这是正确的编码,假设我们正在进行 1-hot 编码

请您参考如下方法:

您可能需要考虑使用 pivot_table 来实现您的目标。

import pandas as pd 
 
df 
 
Out[10]:  
   Instance Cat_Col 
0         1    John 
1         1   Smith 
2         2    Jane 
3         3     Joe 
 
df['count'] = 1 
df.pivot('Instance', 'Cat_Col', 'count').fillna(0) 
 
Out[11]:  
Cat_Col    Jane   Joe   John   Smith 
Instance                             
1             0     0      1       1 
2             1     0      0       0 
3             0     1      0       0 

如果您更喜欢使用get_dummies,

result = pd.get_dummies(df.Cat_Col) 
result['Instance'] = df.Instance 
result = result.set_index('Instance') 
result.groupby(level=0).apply(max) 
 
Out[26]:  
           Jane   Joe   John   Smith 
Instance                             
1             0     0      1       1 
2             1     0      0       0 
3             0     1      0       0