简体   繁体   中英

Creating new binary columns from single string column in pandas

I've seen this before and simply can't remember the function.

Say I have a column "Speed" and each row has 1 of these values:

'Slow', 'Normal', 'Fast'

How do I create a new dataframe with all my rows except the column "Speed" which is now 3 columns: "Slow" "Normal" and "Fast" which has all of my rows labeled with a 1 in whichever column the old "Speed" column was. So if I had:

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

I would not expect this:

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

print df['Slow'].ix[0]
>0

You can do this easily with 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

Here is one solution:

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)

This has another method:

df           = pd.DataFrame(['Slow','Fast','Normal','Normal'],columns=['Speed'])
df['Normal'] = np.where(df['Speed'] == 'Normal', 1 ,0)
df['Fast']   = np.where(df['Speed'] == 'Fast', 1 ,0)
df['Slow']   = np.where(df['Speed'] == 'Slow', 1 ,0)

df 
     Speed  Normal  Fast  Slow
0    Slow       0     0     1
1    Fast       0     1     0
2  Normal       1     0     0
3  Normal       1     0     1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM