使用 pandas 在数据框中创建动态列 [英] Create dynamic columns in dataframe using pandas

查看:79
本文介绍了使用 pandas 在数据框中创建动态列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从此熊猫数据框创建动态列.

How to create dynamic columns from this pandas dataframe.

 Name, Sex
    a, M
    b, F
    c, M
    d, F

预期的数据框:

Name, M, F
a, 1, 0
b, 0, 1
c, 1, 0
d, 0, 1

我已经尝试过pandas.pivot()了,但是没有用,你们能建议点什么吗.

I have tried pandas.pivot() but of no use, could you guys suggest something.

推荐答案

使用获取假人:

pd.concat([df['Name'], df['Sex'].str.get_dummies()], axis=1)
Out: 
    Name   F   M
0      a   0   1
1      b   1   0
2      c   0   1
3      d   1   0


df['Sex'].str.get_dummies()生成虚拟对象:


df['Sex'].str.get_dummies() generates the dummies:

df['Sex'].str.get_dummies()
Out: 
    F   M
0   0   1
1   1   0
2   0   1
3   1   0

,然后可以使用pd.concat将结果与名称列组合.

and then you can use pd.concat to combine the result with the name column.

这篇关于使用 pandas 在数据框中创建动态列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆