1

Can someone help me with the below Python/pandas pivoting?

I'm cleaning up a dataset with 95 columns. I want to pivot 10 of those columns into 2 columns within the table.

How do I do this in Python?

Example:

In the below, I want to pivot swimming, walking, cycling and running into columns activity & yes_no.

dummy_df = pd.DataFrame({
    "name":["Sally", "Jim", "Bob", "Julie", "Pat"],
    "age":[30, 20, 25, 50, 65],
    "city":["Edinburgh", "Glasgow", "Aberdeen", "Dundee", "Perth"],
    "keep_fit":["Yes", "Yes", "No", "No", "Yes"],
    "swimming":["Yes", "No", "No", "No", "No"],
    "walking":["No", "Yes", "No", "Yes", "No"],
    "cycling":["Yes", "Yes", "Yes", "Yes", "No"],
    "running":["No", "No", "Yes", "No", "No"],
})
Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
Kerr McIntosh
  • 121
  • 1
  • 2
  • 9

1 Answers1

1

You need pd.melt:

df1 = pd.melt(dummy_df,id_vars=['name','age','city'],
              var_name='activity',
              value_name='yes_no')


  name  age       city  activity yes_no
0   Sally   30  Edinburgh  keep_fit    Yes
1     Jim   20    Glasgow  keep_fit    Yes
2     Bob   25   Aberdeen  keep_fit     No
3   Julie   50     Dundee  keep_fit     No
4     Pat   65      Perth  keep_fit    Yes
5   Sally   30  Edinburgh  swimming    Yes
6     Jim   20    Glasgow  swimming     No
7     Bob   25   Aberdeen  swimming     No
8   Julie   50     Dundee  swimming     No
9     Pat   65      Perth  swimming     No
10  Sally   30  Edinburgh   walking     No
11    Jim   20    Glasgow   walking    Yes
12    Bob   25   Aberdeen   walking     No
13  Julie   50     Dundee   walking    Yes
14    Pat   65      Perth   walking     No
15  Sally   30  Edinburgh   cycling    Yes
16    Jim   20    Glasgow   cycling    Yes
17    Bob   25   Aberdeen   cycling    Yes
18  Julie   50     Dundee   cycling    Yes
19    Pat   65      Perth   cycling     No
20  Sally   30  Edinburgh   running     No
21    Jim   20    Glasgow   running     No
22    Bob   25   Aberdeen   running    Yes
23  Julie   50     Dundee   running     No
24    Pat   65      Perth   running     No
halfer
  • 19,824
  • 17
  • 99
  • 186
Umar.H
  • 22,559
  • 7
  • 39
  • 74