0

I have a dataframe dfon cafeteria food options:

Meal           Food         Cooked      Percentage 

Breakfast      Yes           Attended      1.00
Breakfast      Apple         No            .25
Breakfast      Oatmeal       Yes           .55
Breakfast      Skipped       Not           .20
Lunch          Yes           Attended      1.00
Lunch          Salad         No            .42
Lunch          Pizza         Yes           .48
Lunch          Skipped       Not           .10

I have tried pd.get_dummies() package, but that gives a binary encoding to the Cooked category column. I want to transform my dataset as such:

Meal           Food         Cooked      Percentage   No    Yes    Not 

Breakfast      Yes           Attended      1.00     .25     .55    .20
Breakfast      Apple         No            .25      .25     .55    .20
Breakfast      Oatmeal       Yes           .55      .25     .55    .20
Breakfast      Skipped       Not           .20      .25     .55    .20
Lunch          Yes           Attended      1.00     .42     .48    .10
Lunch          Salad         No            .42      .42     .48    .10
Lunch          Pizza         Yes           .48      .42     .48    .10
Lunch          Skipped       Not           .10      .42     .48    .10

Hence, I am trying to transpose values of one column into new columns, based on values in a second column.

1
  • last row lunch or breakfast Commented Apr 17, 2021 at 0:32

1 Answer 1

1

Let us try pivot then reindex + join

s = df.pivot('Meal','Cooked','Percentage').reindex(df.Meal)
s.index = df.index
df = df.join(s)
df
Out[124]: 
        Meal     Food    Cooked  Percentage  Attended    No  Not   Yes
0  Breakfast      Yes  Attended        1.00       1.0  0.25  0.2  0.55
1  Breakfast    Apple        No        0.25       1.0  0.25  0.2  0.55
2  Breakfast  Oatmeal       Yes        0.55       1.0  0.25  0.2  0.55
3  Breakfast  Skipped       Not        0.20       1.0  0.25  0.2  0.55
4      Lunch      Yes  Attended        1.00       1.0  0.42  0.1  0.48
5      Lunch    Salad        No        0.42       1.0  0.42  0.1  0.48
6      Lunch    Pizza       Yes        0.48       1.0  0.42  0.1  0.48
7      Lunch  Skipped       Not        0.10       1.0  0.42  0.1  0.48
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.