如何通过pandas get_dummies()方法为某些列创建虚拟对象? [英] how to create dummies for certain columns by pandas get_dummies() method?
本文介绍了如何通过pandas get_dummies()方法为某些列创建虚拟对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
df = pd.DataFrame({'A': ['x', 'y', 'x'], 'B': ['z', 'u', 'z'],
'C': ['1', '2', '3'],
'D':['j', 'l', 'j']})
我只希望A列和D列获得不是B列的虚拟变量.如果我使用pd.get_dummies(df)
,则所有列都变成了虚拟变量.
I just want Column A and D to get dummies not for Column B. If I used pd.get_dummies(df)
, all columns turned into dummies.
我希望最终结果包含所有column,这意味着C列和B列都退出了,就像'A_x','A_y','B','C','D_j','D_l'
一样.
I want the final result containing all of columns , which means column C and column B exit,like 'A_x','A_y','B','C','D_j','D_l'
.
推荐答案
使用带有必需参数的get_dummies()可以不进行串联操作
It can be done without concatenation, using get_dummies() with required parameters
In [294]: pd.get_dummies(df, prefix=['A', 'D'], columns=['A', 'D'])
Out[294]:
B C A_x A_y D_j D_l
0 z 1 1.0 0.0 1.0 0.0
1 u 2 0.0 1.0 0.0 1.0
2 z 3 1.0 0.0 1.0 0.0
这篇关于如何通过pandas get_dummies()方法为某些列创建虚拟对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文