样式化熊猫DataFrame时如何使索引从1开始

时间:2020-05-05 18:00:12

标签: python css python-3.x pandas

pandas DataFrame中设置Python的样式后。我注意到索引从0开始。如何使它从1开始。

我尝试做df.index = np.arange(1, len(df)),但给我一个错误:ValueError: Length mismatch: Expected axis has 1119 elements, new values have 1118 elements

这是我的代码供您审核:

from IPython.display import HTML

df.index = np.arange(1, len(df))

def hover(hover_color="#FF5733"):
    return dict(selector="tbody tr:hover",
            props=[("background-color", "%s" % hover_color)])

styles = [
    #table properties
    dict(selector=" ", 
         props=[("margin","0"),
                ("font-family",'calibri'),
                ("border-collapse", "collapse"),
                ("border","none"),
                ("border", "2px solid #ccf")
                   ]),

    #header color - optional
    dict(selector="thead", 
         props=[("background-color","#489AF3")
               ]),

    #background shading
    dict(selector="tbody tr:nth-child(even)",
         props=[("background-color", "#fff")]),
    dict(selector="tbody tr:nth-child(odd)",
         props=[("background-color", "#eee")]),

    #cell spacing
    dict(selector="td", 
         props=[("padding", ".5em")]),

    #header cell properties
    dict(selector="th", 
         props=[("font-size", "130%"),
                ("text-align", "center")]),

    #caption placement
    dict(selector="caption", 
         props=[("caption-side", "bottom")]),

    #render hover last to override background-color
    hover()
]


# this forces grey background on header
styler = df.style.set_properties(**{'text-align': 'center'}).set_table_styles(styles)

# HTML string
html = styler.render()

# save html
with open('file2.html', 'w') as f:
    f.write(html)

1 个答案:

答案 0 :(得分:1)

正如评论df.index = np.arange(1, len(df)+1)中提到的那样,