我已经设计了数据帧输出的样式,并让它在 Jupyter Notebook 中显示我想要的方式,但我遇到问题,找不到一种将其保存为图像的好方法。我努力了https://pypi.org/project/dataframe-image/ https://pypi.org/project/dataframe-image/但我的工作方式似乎是一个 NoneType ,因为它是一个样式器对象,并且在尝试使用这个库时出错。
这只是整个代码的一个片段,旨在循环几个“col_names”,我想将它们保存为图像(以解释一些编码)。
import pandas as pd
import numpy as np
col_name = 'TestColumn'
temp_df = pd.DataFrame({'TestColumn':['A','B','A',np.nan]})
t1 = (temp_df[col_name].fillna("Unknown").value_counts()/len(temp_df)*100).to_frame().reset_index()
t1.rename(columns={'index':' '}, inplace=True)
t1[' '] = t1[' '].astype(str)
display(t1.style.bar(subset=[col_name], color='#5e81f2', vmax=100, vmin=0).set_table_attributes('style="font-size: 17px"').set_properties(
**{'color': 'black !important',
'border': '1px black solid !important'}
).set_table_styles([{
'selector': 'th',
'props': [('border', '1px black solid !important')]
}]).set_properties( **{'width': '500px'}).hide_index().set_properties(subset=[" "], **{'text-align': 'left'}))
[OUTPUT]
能够更改我在样式器对象上使用数据帧图像的方式并使其正常工作。将其传递到 export() 函数而不是直接从对象中调用它似乎是执行此操作的正确方法。
The .render() did get the HTML but was often losing much of the styling when converting it to image or when not viewed with Ipython HTML display. See comparision below.
工作代码:
import pandas as pd
import numpy as np
import dataframe_image as dfi
col_name = 'TestColumn'
temp_df = pd.DataFrame({'TestColumn':['A','B','A',np.nan]})
t1 = (temp_df[col_name].fillna("Unknown").value_counts()/len(temp_df)*100).to_frame().reset_index()
t1.rename(columns={'index':' '}, inplace=True)
t1[' '] = t1[' '].astype(str)
style_test = t1.style.bar(subset=[col_name], color='#5e81f2', vmax=100, vmin=0).set_table_attributes('style="font-size: 17px"').set_properties(
**{'color': 'black !important',
'border': '1px black solid !important'}
).set_table_styles([{
'selector': 'th',
'props': [('border', '1px black solid !important')]
}]).set_properties( **{'width': '500px'}).hide_index().set_properties(subset=[" "], **{'text-align': 'left'})
dfi.export(style_test, 'successful_test.png')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)