Search code examples
pandaspython-3.6pandasql

Pandas dataframe transpose with column name instead of index throws ValueError


I am trying to show actual column name in json after dataframe has been transposed, below code works for LIMIT 3 in sql but fails if I try LIMIT 5 Any thoughts please?

from pandasql import *

pysqldf = lambda q: sqldf(q, globals())

q1 = """
SELECT
 beef as beef, veal as veal, pork as pork, lamb_and_mutton as lamb
FROM
 meat m
LIMIT 5;
"""

meat = load_meat()

df = pysqldf(q1)
#print(df.to_json(orient='records'))

hdf = pd.DataFrame(df)
print(hdf.T.reset_index().set_axis(range(len(hdf.columns)), axis=1, inplace=False).to_json(orient='records'))

ERROR

    'values have {new} elements'.format(old=old_len, new=new_len))
ValueError: Length mismatch: Expected axis has 6 elements, new values have 4 elements

Solution

  • After you T and reset_index , you have add one more columns , at the same time, the length of index is equal to columns before transposed, so you should using shape

    print(hdf.T.reset_index().set_axis(range(hdf.shape[0]+1), axis=1, inplace=False).to_json(orient='records'))