Pivoting in Pandas

Asked

Viewed 41 times

3

Hey there, guys. I have a table in pandas and would like to turn the values in the column DE_ANALITO into columns whose values would be what is in the column DE_RESULTADO.

+----+----------------------------------+--------------------+----------------+
|    | ID_PACIENTE                      | DE_ANALITO         | DE_RESULTADO   |
|----+----------------------------------+--------------------+----------------|
|  0 | 3487791F44C34B421C932DC8616A8437 | Fosfatase Alcalina | 106            |
|  1 | 3487791F44C34B421C932DC8616A8437 | Gama-GT            | 33             |
|  2 | 3487791F44C34B421C932DC8616A8437 | ALT (TGP)          | 51             |
|  3 | 3487791F44C34B421C932DC8616A8437 | DHL                | 530            |
|  4 | 3487791F44C34B421C932DC8616A8437 | Proteína C-Reativa | 1,84           |
+----+----------------------------------+--------------------+----------------+

I tried to:

exames.pivot(index="ID_PACIENTE", columns="DE_ANALITO", values="DE_RESULTADO")

But returns the error:

ValueError: Index contains duplicate entries, cannot reshape

In the documentation of the pivot method is given as an example the pivoting of a table with the same format as mine, with index column also with repeated values. I don’t know what I’m doing wrong

1 answer

1

See if this way works for you

df.pivot_table(index = 'ID_PACIENTE', columns = 'DE_ANALITO', values = 'DE_RESULTADO', aggfunc = ''.join).reset_index().rename_axis(None, axis = 1)

or

df.pivot(index = 'ID_PACIENTE', columns = 'DE_ANALITO', values = 'DE_RESULTADO').reset_index().rename_axis(None, axis = 1)

Exit:

                         ID_PACIENTE    ALT(TGP)    DHL Fosfatase Alcalina  Gama-GT Proteína C-Reativa
0   3487791F44C34B421C932DC8616A8437    51          530               106        33   1,84

About the error

Valueerror: Index contains Duplicate Entries, cannot reshape

You need to check your database because there are duplicate values and this way you need to treat them

Browser other questions tagged

You are not signed in. Login or sign up in order to post.