从pandas中的单个字符串列创建新的二进制列

use*_*719 7 python pandas

我以前见过这个,根本记不住这个功能.

假设我有一个列"速度",每行有以下1个值:

'Slow', 'Normal', 'Fast'
Run Code Online (Sandbox Code Playgroud)

如何创建一个包含所有行的新数据框,除了"速度"列,现在是3列:"慢""正常"和"快速",其中所有行都标记为1,无论哪一列都是旧的"速度" "专栏是.所以,如果我有:

print df['Speed'].ix[0]
> 'Normal'
Run Code Online (Sandbox Code Playgroud)

我不指望这个:

print df['Normal'].ix[0]
>1

print df['Slow'].ix[0]
>0
Run Code Online (Sandbox Code Playgroud)

jor*_*ris 11

您可以使用pd.get_dummies(docs)轻松完成此操作:

In [37]: df = pd.DataFrame(['Slow', 'Normal', 'Fast', 'Slow'], columns=['Speed'])

In [38]: df
Out[38]:
    Speed
0    Slow
1  Normal
2    Fast
3    Slow

In [39]: pd.get_dummies(df['Speed'])
Out[39]:
   Fast  Normal  Slow
0     0       0     1
1     0       1     0
2     1       0     0
3     0       0     1
Run Code Online (Sandbox Code Playgroud)


aha*_*aha 6

这是一种解决方案:

df['Normal'] = df.Speed.apply(lambda x: 1 if x == "Normal" else 0)
df['Slow'] = df.Speed.apply(lambda x: 1 if x == "Slow" else 0)
df['Fast'] = df.Speed.apply(lambda x: 1 if x == "Fast" else 0)
Run Code Online (Sandbox Code Playgroud)