Как сделать так, чтобы ваш индекс начинался с 1 при стилизации вашего pandas DataFrame - PullRequest
1 голос
/ 05 мая 2020

После стилизации моего 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 Ответ

1 голос
/ 05 мая 2020

Как упоминалось в комментариях, df.index = np.arange(1, len(df)+1) работает

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...