我通过使用 pandas
crosstab
函数获得以下数据帧输出,然后执行 tohtml() 以获取表格形式。但我需要先让我的 DF 处于正确的形式
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_非空 | 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 |
是否有任何解决方案可以在数据框中以预期格式获取表头? TIA
代码:
out = pd.crosstab(
df1["lurn_FLS"],
df1["LOCALITY"],
margins=True,
margins_name="Total",
colnames=[None],
).reset_index()
out["Percentage"] = (
out["Total"].map(lambda x: (x / out["Total"].iloc[-1]) * 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)