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 pandasq
Solution 1:
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'))
Solution 2:
Try this:
df.T.reset_index()\
.set_axis(range(len(df)+1), axis=1, inplace=False)\
.to_json(orient='records')
Note: The issue is renaming the columns after the transpose, you need the length to be the number of rows in the original dataframe plus 1 for index.
Output:
'[{"0":"beef","1":0,"2":4,"3":8,"4":12,"5":16},{"0":"veal","1":1,"2":5,"3":9,"4":13,"5":17},{"0":"pork","1":2,"2":6,"3":10,"4":14,"5":18},{"0":"lamb","1":3,"2":7,"3":11,"4":15,"5":29}]'
Post a Comment for "Pandas Dataframe Transpose With Column Name Instead Of Index Throws Valueerror"