0
$\begingroup$

Input: I have csv file like below as input....

ID, Year,Specialty,AgeRange,PlaceSvc,Count, Group
101,2009,Internal,  20-29,  Office,     0,  PRGNCY
101,2010,Emergency, 20-29,  Urgent Care,0,  GIOBSENT
101,2011,Internal,  20-29,  Office,     0,  GYNEC1
102,2010,Other,     30-39,  Office,     1,  PRGNCY
102,2010,Laboratory,30-39,  Independent,1,  MSC2a3
103,2009,Laboratory,30-39,  Independent,1,  MSC2a3
103,2011,Other,     30-39,  Office,     0,  PRGNCY

Output: I want output like below...

ID,Year,Specialty_Internal,Specialty_Emergency,Specialty_Labrotory,Specialty_Other,Age20_29,Age30_39,PlaceSvc_Urgent,PlaceSvc_Office,PlaceSvc_Independent,Count,GroupPrgncy,GroupGiobsent,GroupGynec1,GroupMsc2a3

101,2009,1,0,0,0,1,0,0,1,0,0,1,0,0,0
101,2010,0,1,0,0,1,0,1,0,0,0,0,1,0,0
101,2011,1,0,0,0,1,0,0,1,0,0,0,0,1,0
102,2010,0,0,1,1,0,1,0,1,1,2,1,0,0,1
103,2009,0,0,1,0,0,1,0,0,1,1,0,0,0,1
103,2011,0,0,0,1,,1,0,1,0,0,1,0,0,0

How can i do this by pandas? or is there any other techinque to do this?

$\endgroup$
2
$\begingroup$

You want pandas.get_dummies.

If you call get_dummies on a categorical column, it will output the binary dummy variables you're looking for. You should then be able to merge this with your original DataFrame on the index, or construct a new DataFrame using only the columns you want.

|improve this answer|||||
$\endgroup$
  • $\begingroup$ It is making all column as categorical column. Is it possible to not to make Year column as category? $\endgroup$ – An0mn Mar 27 '17 at 9:51
  • $\begingroup$ Yes. Filter out your year column before feeding it into the get_dummies function. You might want to look at DataFrame.merge and pandas.concat if you're not already familiar with them, as this will let you construct a new DataFrame using your new columns. $\endgroup$ – R Hill Mar 27 '17 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.