need to create a matrix/pivot table in python

Question:

Having a data frame as below.

df1 = pd.DataFrame({'Name1':['A','A','A','B','B','C','C','C'],
                    'Name2':['B','C','D','C','D','D','A','B'],'Marks2':[10,20,6,50, 88,23,140,9]})
df1

I need to create an output in the following format:
The index should only contain value A from Name1.

IMG

Asked By: Jack

||

Answers:

filter and pivot:

df1.query('Name1 == "A"').pivot('Name1', 'Name2', 'Marks2')

output:

Name2   B   C  D
Name1           
A      10  20  6

NB. to remove the indexes names, add .rename_axis(index=None, columns=None).

Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.