用列名而不是索引转置的 pandas 数据框会引发ValueError [英] Pandas dataframe transpose with column name instead of index throws ValueError

查看:343
本文介绍了用列名而不是索引转置的 pandas 数据框会引发ValueError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在转置数据框后在json中显示实际的列名,下面的代码适用于sql中的LIMIT 3,但是如果尝试LIMIT 5有什么想法的话会失败?

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'))

错误

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

推荐答案

Treset_index之后,又添加了一个columns,同时index的长度等于columns在转置之前,因此您应该使用shape

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'))

这篇关于用列名而不是索引转置的 pandas 数据框会引发ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆