Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

need to create a matrix/pivot table in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading