dataframe - 在 Jupyter Notebook 的列标题中显示带有数学符号的 DataFrame
问题描述
我有一个 DataFrame,我想用聚合函数的希腊名称显示它。
df=pd.DataFrame(
[["A",1,2],["A",3,4],["B",5,6],["B",7,8]],
columns=["AB","C", "N"]
)
df=df.groupby(df.AB).agg({
"C":["count", "sum", "mean", "std"],
"N":["sum", "mean", "std"]
})
看起来像:
我想制作如下所示的东西:
我已经能够生产:
和
import pandas as pd
import matplotlib.pyplot as plt
data = [[str(cell) for cell in row] for row in df.values]
columns = [
r"Count",
r"C $\Sigma$",
r"C $\bar{x}$",
r"C $\sigma$",
r"N $\Sigma$",
r"N $\bar{x}$",
r"N $\sigma$"]
rows = ["A", "B"]
the_table = plt.table(cellText=data,
rowLabels=rows,
colLabels=columns)
the_table.scale(4,4)
the_table.set_fontsize(24)
plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
plt.tick_params(axis='y', which='both', right=False, left=False, labelleft=False)
for pos in ['right','top','bottom','left']:
plt.gca().spines[pos].set_visible(False)
该df.to_latex()
功能看起来可能足以满足我的目的,但它呈现为 jupyter 不支持的表格。
感谢下面的 Elliot,这样的东西非常好用
substitutions = {
"sum":"\u03a3",
"mean":"\u03bc",
"std":"\u03c3",
True:"\u2705",
False:"\u274c",
"count":"N",
}
pretty = df.\
rename(substitutions, axis=0).\
rename(substitutions, axis=1)
与:
%%HTML
<style type="text/css">
table.dataframe td, table.dataframe th {
border: 1px black solid !important;
color: black !important;
}
th {
text-align: center !important;
}
</style>
可以生产
解决方案
您可以使用 Unicode 字符来获取您想要的字符标题,而无需使用to_latex()
.
如果您想要边框,您可以使用to_html
自定义选项来格式化表格。
推荐阅读
- opencv - 无法在 jupyter notebook 中导入 cv2 包
- iis - IIS 反向代理背后的 Keycloak
- php - Chart.js 中的日期时间选择器
- python - 在python中使用循环添加所有输入后,如何垂直打印所有计算元素?
- java - 在 Spring Retryable 中的所有尝试之前退出
- python - 使用 discord.py 嵌入多个页面
- svn - TortoiseSVN:文件在日志中标记为“修改”和“添加”
- android - Android首选项屏幕主题不起作用
- python - 使用python分隔列
- elasticsearch - 我想在 Elastic Search 的数组中搜索字段