Home > other >  Python Dataframe using Columns as Index
Python Dataframe using Columns as Index

Time:09-09

I am relatively new to Python and I've run in to a problem that I cannot seem to search my way out of. I have written a function to query a third-party API. The function runs as expected and retrieves the correct results. However, my dataframe display returns the results with my columns and rows transposed. I have used this same function before without issue. I know I can transpose them to the correct position, but since I want to use this function as part of a larger function it is important that the query return the values with the columns and rows as intended.

I've included my snippet below as well as the results and desired outcome.

import pandas as pd

def get_tiering():
    df = vendorAPI.getportfoliocustomcolumns('prod').as_dataframe()
    records = df.to_dict('records')
    return {rec['Patient']: rec for rec in records}

tiersdf = pd.DataFrame(get_tiering())

print(tiersdf)

current output

[6 rows x 198 columns]

desired output

[198 rows x 6 columns]

I am wondering if there is some DataFrame setting that I inadvertently changed? I am using Spyder version 2.2 with Python 3.9. Any guidance you can provide would be appreciated.

Thank you for your time.

CodePudding user response:

Did you try tiersdf.T?

This is my sample df

        p1  p2  p3
height  65  66  5
weight  62  22  6
age     32  55  8
bp      12  44  6
hr      2   8   3

and i got this after doing transform

     height weight  age bp  hr
p1    65    62      32  12  2
p2    66    22      55  44  8
p3     5    6       8   6   3

CodePudding user response:

I would suggest you try to change

records = df.to_dict('records')
return {rec['Patient']: rec for rec in records}

to

return df.transpose().to_dict('series')

Please, let me know if it works. Otherwise, please let us know the exact output of vendorAPI.getportfoliocustomcolumns('prod')

  • Related