-1

I have numeric data within Student marks and I would like to have single record for every Student with all his related data spread into many records.

df = pd.DataFrame([('Adel', "Subj1", 3.50  ,2.57),
                   ('Adel', "Subj2", 2.75  ,3.6  ),

                   ('Alexa',"Subj1", 1.75  ,3.25) ,
                   ('Alexa',"Subj3", 3.15  ,2.25) ], 
                  columns=('Name', "Subj","Med", "Ach" ))

I developed a long loop statement and have the underneath table, but I thought there is maybe a better way . enter image description here

Any shortcut for a such pivot table? Of course, I may have missing Data since not all Students attend all Courses.

SAM.Am
  • 187
  • 14
  • 1
    Did you check https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html? – Itamar Mushkin Jan 19 '20 at 10:25
  • 1
    Does this answer your question? [How to pivot a dataframe](https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe) – Itamar Mushkin Jan 19 '20 at 10:26
  • @Itamar I updated may question. The link above answers partially the question but still keep a single ID record splitted. I added the kind of records I expected to have. – SAM.Am Jan 19 '20 at 11:57

1 Answers1

2

You can do:

df2=df.pivot(index="Name", columns="Subj", values=["Med", "Ach"]).swaplevel(0,1, axis=1)
#flatten index - I assumed that's what you're going for:
df2.columns=["_".join(el) for el in df2.columns] 

Output:

       Subj1_Med  Subj2_Med  ...  Subj2_Ach  Subj3_Ach
Name                         ...
Adel        3.50       2.75  ...        3.6        NaN
Alexa       1.75        NaN  ...        NaN       2.25
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
  • 1
    THANKS, This is what I want, I guess my question was not fruitless , and don't know why I got that vote for it. Any how, Thanks, – SAM.Am Jan 19 '20 at 15:15