python - 使用 Pandas 在数据框中创建动态列

标签 python pandas

如何从这个 pandas 数据框创建动态列。

 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() 但没用,你们能给我些建议吗?

最佳答案

使用获取假人:

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()
Out: 
    F   M
0   0   1
1   1   0
2   0   1
3   1   0

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

关于python - 使用 Pandas 在数据框中创建动态列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38701573/

相关文章:

python - 以编程方式为 pd.melt 选择列

python - 高级数组/数据帧切片(numpy/pandas)

python - 我是一名 .NET 程序员。 Python 和/或 Ruby 的具体用途是什么可以提高我的工作效率?

python - 使用 NLP 进行地址拆分

python - 有没有一种有效的方法来判断是否在 Tkinter 文本小部件中选择了文本?

python - 根据其他列条件更新列

Python:如何找到匹配的数据条目并在两个数据集之间执行高效计算

python - 如何限制beautifulsoup中select标签的结果?

Python peewee.ImproperlyConfigured : MySQL driver not installed

python - 如何获取 1 列值并将其中一些值放入基于 bool 标志列的新列中?