0

I have a column in dataframe(df['Values') with 1000 rows with repetitive codes A30, A31, A32, A33, A34. I want to create five separate columns with headings colA30, colA31, colA32, colA33, colA34 in the same dataframe(df) with values 0 or 1 in the new five columns created based on if the row is anyone of codes in df['Values'].

for Ex: df

Values  colA30 colA31 colA32 colA33 colA34
 A32       0     0      1      0      0
 A30       1     0      0      0      0
 A31       0     1      0      0      0
 A34       0     0      0      0      1
 A33       0     0      0      1      0

So if a row in df['Values'] is A32 then colA32 should be 1 and all other columns should be 0's and so on for rest of columns in df['Values'].

I did in the following way. But, is there anyway to do it in one shot as i have multiple columns with several codes for which multiple columns are to be created.

df['A30']=df['Values'].map(lambda x : 1 if x=='A30' else 0)

df['A31']=df['Values'].map(lambda x : 1 if x=='A31' else 0)

df['A32']=df['Values'].map(lambda x : 1 if x=='A32' else 0)

df['A33']=df['Values'].map(lambda x : 1 if x=='A33' else 0)

df['A34']=df['Values'].map(lambda x : 1 if x=='A34' else 0)
1
  • 3
    Looking for pd.get_dummies(df.Values)? Commented Nov 30, 2016 at 16:45

1 Answer 1

2

You can do this in many ways :

In pandas there is a function called pd.get_dummies() that allows you to convert each categorical data to a binary data. Apply it to your categorical column and then concatenate the dataframe obtained with the original one. Here is the link to the documentation.

Another way would be to use the library sklearn and its OneHotEncoder. It does exactly the same as above but the objects is not the same. You should use the instance of your OneHotEncoder class to fit it to your categorical data.

For your case I'd use pd.get_dummies(), it's simpler to use.

Sign up to request clarification or add additional context in comments.

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.