提问人:Ashu 提问时间:11/17/2023 最后编辑:Ashu 更新时间:11/17/2023 访问量:45
pandas Dataframe 中的多索引
MultiIndexing in pandas Dataframe
问:
我通过使用 pandas 函数,然后执行 tohtml() 来获取表格形式,从而获得以下数据帧输出。但我需要先让我的 DF 以正确的形式出现crosstab
out = pd.crosstab(df1[lurn_FLS'], df1['LOCALITY'])
out['Total'] = out.sum(axis=1)
total_sum = out[ 'Total'].sum()
out['Percentage'] = ((out ['Total'/total_sum) *100).round(2)
print(out)
地区 | mbn:match_both_non-空 | xne:不匹配,既不为空 | 总 | 百分比 |
---|---|---|---|---|
lurn_fls | ||||
-------- | ------------------------- | -------------------------- | ------ | ------------ |
1 | 210 | 300 | 510 | 21 |
2 | 310 | 400 | 710 | 50 |
我希望表格标题如下所示,实际的列标题位于表格的第一行
| Locality | | | | |
| -------- | -------------------------| -------------------------- | ------|------------|
| lurn_fls | mbn:match_both_non-empty | xne:mismatch neither empty | Total | Percentage |
| -------- | -------------------------| -------------------------- | ------|------------|
| 1 | 210 | 300 | 510 | 21 |
| 2 | 310 | 400 | 710 | 50 |
是否有任何解决方案可以在数据帧中以预期格式获取表头?短暂性投资安全
答:
1赞
cxywz
11/17/2023
#1
像这样的html?在这里输入图片描述
法典:
out = pd.crosstab(
df1["lurn_FLS"],
df1["LOCALITY"],
margins=True,
margins_name="Total",
colnames=[None],
).reset_index()
out["Percentage"] = out["Total"].divide(out["Total"].iloc[-1]).mul(100).round(2)
)
newcols = out.columns.map(lambda x: ("LOCALITY", x))
out.columns = newcols
out = out.iloc[:-1]
out.to_html("out.html", index=False)
评论
'Total'
reset_index