9

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

3 Answers 3

14

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
Sign up to request clarification or add additional context in comments.

1 Comment

get_dummies was it! Thanks!
6

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)

Comments

2

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

   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.