我正在尝试在转置数据帧后在json中显示实际的列名,下面的代码适用于sql的LIMIT 3,但如果我尝试LIMIT 5,请尝试一下会失败吗?
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
答案 0 :(得分:2)
在 override func viewDidAppear(_ animated: Bool) {
UIApplication.shared.keyWindow?.rootViewController = self
self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
prevVC.reloadViewFromnib()
prevVC.dismiss(animated: false, completion: nil)
UserDefaults.standard.set(0, forKey: "since_The_Last_Ad")
}
extension UIViewController {
func reloadViewFromnib() {
let parent = view.superview
view.removeFromSuperview()
view = nil
parent?.addSubview(view) // This line causes the view to be reloaded
}
}
和T
之后,您又添加了一个reset_index
,同时columns
的长度等于index
之前的长度换位,所以您应该使用columns
shape
答案 1 :(得分:2)
尝试一下:
df.T.reset_index()\
.set_axis(range(len(df)+1), axis=1, inplace=False)\
.to_json(orient='records')
注意:问题是在转置后重命名列,您需要将长度设为原始数据帧中的行数加上索引的1。
输出:
'[{"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}]'