pandas dataframe-索引列标题较低。为什么?

时间:2018-08-06 06:59:21

标签: python pandas dataframe

我希望索引列标题“日期”与所有其他列在同一行。现在,它低了一行。我该如何解决?

enter image description here

@app.route('/closeprice', methods=['POST']) #route tells Flask what URL should trigger the function
def closeprice():    
    tickersym = request.form['ticker']
    pandas_ds = get_historical_data(tickersym, start, end, output_format='pandas')
    pandas_ds['closechg']=pandas_ds.close.pct_change() #closing daily change 
    server_data = (pandas_ds.style.applymap(color_negative_red, subset=['closechg']).format({'closechg':"{:.2%}"})).render()
    return render_template('view.html',tickersym=tickersym,tables=[server_data],titles = tickersym)    

2 个答案:

答案 0 :(得分:0)

import pandas as pd
import numpy as np

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=["open","high","low","close"])

new_dates=df.index.set_names("date")
df.index=new_dates

writer = pd.ExcelWriter('Save_Excel.xlsx')
df.to_excel(writer,'page_1',float_format='%.5f')
writer.save()

我试图复制date的值,并在表中声明一个名为'date'的新列,然后重置索引,我得到了相同的结果。

enter image description here

通过以“ xlsx”格式保存表格,可以得到所需的内容。

答案 1 :(得分:0)

尝试以下操作:

df.columns.name = df.index.name
df.index.name = None