0

I have a data frame that looks like this:

ethnicity_name enrollment teacher_salary ethnicity_percent
African_American 513 102000 .10
Caucasian 513 102000 .26
Hispanic 513 102000 .64

I need to "unstack" the first column (ethnicity_name) into three additional columns, and fill the values of those columns with "ethnicity_percent" values.

The final dataframe should look like this:

enrollment teacher_salary African_American Caucasian Hispanic
513 102000 .10 .26 .64

I can think of the following two ways of doing this, which are hackneyed:

  1. pd.get_dummies and then df.map on the original names column to the values column
  2. turn the 'ethnicity_name' column into an index, and unstack, and then map

I'm a beginner, so I have faith that there must be some better way. TIA.

elby
  • 1
  • 2
    try `pivot` : ``df.pivot(['enrollment', 'teacher_salary'], 'ethnicity_name', 'ethnicity_percent')`` – sammywemmy Aug 29 '21 at 23:05
  • Thank you! Let's say that I had another pair of columns in the same dataframe, with the same issue, would the syntax be: df.pivot(['enrollment', 'teacher_salary'], [('ethnicity_name', 'ethnicity_percent'),('hypothetical_name','hypothetical_value')]) ? – elby Aug 29 '21 at 23:36

0 Answers0