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

Pivot table based on the first value of the group in Pandas

Have the following DataFrame:

enter image description here

I’m trying to pivot it in pandas and achieve the following format:

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

enter image description here

Actually I tried the classical approach with pd.pivot_table() but it does not work out:

pd.pivot_table(df,values='col2', index=[df.index], columns = 'col1')

Would be appreciate for some suggestions 🙂 Thanks!

>Solution :

You can use pivot and then dropna for each column:

>>> df.pivot(columns='col1', values='col2').apply(lambda x: x.dropna().tolist()).astype(int)
col1  a  b  c
0     1  2  9
1     4  5  0
2     6  8  7
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