Home > Net >  need to create a matrix/pivot table in python
need to create a matrix/pivot table in python

Time:09-13

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

CodePudding user response:

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).

  • Related