gpt4 book ai didi

python-2.7 - Pandas / python : split column based on a dictionary

转载 作者:行者123 更新时间:2023-12-03 18:36:50 26 4
gpt4 key购买 nike

我有一个 Pandas 数据框,其中有一列包含逗号分隔值:

a,c,f
a,b,c,d,e
c,g,f,b
..

每一行都有不同的长度、不同的顺序和值。这是 a 到 m 的字母。

我想用 0 和 1 将它转换成 13 列:

a b c d e f g h i j k l m
1 0 0 0 0 1 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
0 1 1 1 1 0 0 0 0 0 0 0 0

我如何在 pandas/python 2.7 中有效地做到这一点?我考虑过根据列中是否存在子字符串的测试来创建一个列。但我不敢相信没有更有效的方法来做到这一点 :)

最佳答案

您可以使用 get_dummies如果列是 a:

print df.a
0 a,c,f
1 a,b,c,d,e
2 c,g,f,b
Name: a, dtype: object

print df.a.str.get_dummies(sep=',')
a b c d e f g
0 1 0 1 0 0 1 0
1 1 1 1 1 1 0 0
2 0 1 1 0 0 1 1

关于python-2.7 - Pandas / python : split column based on a dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35748831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com