[英]Python - Pandas - DataFrame - Explode single column into multiple boolean columns based on conditions
Good morning chaps, 早上好,
Any pythonic way to explode a dataframe column into multiple columns with boolean flags, based on some condition (str.contains in this case)? 基于某些条件(在这种情况下为str.contains),使用布尔标志将数据帧列分解为多个列的任何pythonic方法?
Let's say I have this: 假设我有这个:
Position Letter
1 a
2 b
3 c
4 b
5 b
And I'd like to achieve this: 我想实现这个目标:
Position Letter is_a is_b is_C
1 a TRUE FALSE FALSE
2 b FALSE TRUE FALSE
3 c FALSE FALSE TRUE
4 b FALSE TRUE FALSE
5 b FALSE TRUE FALSE
Can do with a loop through 'abc' and explicitly creating new df columns, but wondering if some built-in method already exists in pandas. 可以通过'abc'循环并显式创建新的df列,但想知道pandas中是否已存在某些内置方法。 Number of possible values, and hence number of new columns is variable. 可能的值的数量,因此新列的数量是可变的。
Thanks and regards. 感谢致敬。
use Series.str.get_dummies() : 使用Series.str.get_dummies() :
In [31]: df.join(df.Letter.str.get_dummies())
Out[31]:
Position Letter a b c
0 1 a 1 0 0
1 2 b 0 1 0
2 3 c 0 0 1
3 4 b 0 1 0
4 5 b 0 1 0
or 要么
In [32]: df.join(df.Letter.str.get_dummies().astype(bool))
Out[32]:
Position Letter a b c
0 1 a True False False
1 2 b False True False
2 3 c False False True
3 4 b False True False
4 5 b False True False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.