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

How to pivot without aggregation in python or sql

I want to pivot a table such that each row in the type column is now its own row. Each metric is then a row and the values are the intersection of the metric and type. There are a variable number of types and metrics.Example. I do not want to alter the values in any way with aggregations. Any help with python or sql would be greatly appreciated!

I tried the pivoting function in SQL however I do not want to aggregate any values

Python example:
d = {‘Type’: [‘a’,’a’,’a’,’a’,’a’,’b’,’b’,’b’,’b’,’b’],
‘Metric’: [‘q rate’,’w rate’,’e rate’,’r rate’, ‘t rate’,’q rate’,’w rate’,’e rate’,’r rate’, ‘t rate’],
‘Value’:[1,2,3,4,5,9,8,7,6,5]}
df = pd.DataFrame(data=d)
df

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

SELECT * FROM
(
SELECT Type, Metric, Value
FROM table
)
PIVOT(MAX(Value) FOR Type in (‘List_of_types’))

>Solution :

Since you you have a tag, here is a proposition with pandas.DataFrame.pivot :

out = (
        df
          .pivot(index="Metric", columns="Type")
          .reset_index()
          .droplevel(0, axis=1)
          .rename_axis(None, axis=1)
       )

Output :

print(out)

           a  b
0  e rate  3  7
1  q rate  1  9
2  r rate  4  6
3  t rate  5  5
4  w rate  2  8
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