python - 如何在设计 pandas DataFrame 时使索引从 1 开始

标签 python css python-3.x pandas

在使用 Python 设计我的 pandas DataFrame 后。我注意到索引从 0 开始。如何让它从 1 开始。

我尝试执行 df.index = np.arange(1, len(df)) 但它给了我一个错误:ValueError: Length Mismatch: Expected axis has 1119 elements,新值有 1118 个元素

这是我的代码供您审阅:

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)

最佳答案

正如评论中提到的df.index = np.arange(1, len(df)+1) 可以解决问题

关于python - 如何在设计 pandas DataFrame 时使索引从 1 开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61619838/

相关文章:

python - 如何在嵌套列表中查找元素的索引?

javascript - 使div仅在悬停时滚动

CSS 溢出 : hidden cuts shadow

python-3.x - 在 Python 中将请求发布到 Slack

python - 如何以交互方式将一个代码的输出输入到另一个代码中并从 Pycharm 交互式 python 控制台运行它们?

python - 从带有日期类型的 pandas 列中绘制直方图

javascript - 与 python-shell 和 node.js 的双向通信

html - 响应图像锚定在其容器 div 的顶部

python - 如何使用 openpyxl python 将数据附加到指定行中的 excel 文件?

python - 如何在同一个包中导入 __init__.py 中定义的类?