使用 pandas 在数据框中创建动态列

编程入门 行业动态 更新时间:2024-10-26 22:18:13
本文介绍了使用 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 在数据框中创建动态列

本文发布于:2023-07-20 17:42:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1169650.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框中   动态   数据   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!