第一列左对齐,其他列居中对齐 Pandas table

Left align the first column and center align the other columns in a Pandas table

我正在尝试格式化 Pandas table。我想左对齐第一列并居中对齐 Pandas table 中的其他两列(table header 除外)。

代码:

import pandas as pd
from IPython.display import HTML
df = pd.DataFrame({'Unit': ['Bit', 'Nibble','Byte/Octet', 'Kilobyte', 'Megabyte', 'Gigabyte', 'Terabyte'], 'Abbreviation': ['b', '-', 'B', 'KB', 'MB', 'GB', 'TB'], 'Storage': ['Binary digit, single 0 or 1', '4 bits', '8 bits', '1024 bytes', '1024 KB', '1024 MB', '1024 GB']})
df.style.set_properties(**{'text-align': 'center'})

我正在使用 Google Colab 渲染 table。

结果:

这个table差不多就是我想要的了。我正在尝试打印相同的 table 除了我想隐藏索引号并左对齐第一列,这样我就有一个 table 7 行 + 1 header 和3 列看起来像这样。

我尝试使用 df.style.hide_index() 来隐藏索引号并且它起作用了,但我不知道如何将 df.style.hide_index()df.style.set_properties(**{'text-align': 'center'}) 结合 第一个屏幕截图显示了所有三列居中对齐,我想左对齐第一列,居中对齐第二列和第三列,除了 header 应该使所有三列居中对齐。

table 可以在 Pandas 中通过将两个缺少的格式化条件组合成一个 df 来进行漂亮的格式化。我对原始代码进行了以下两处更改。

  1. 隐藏索引号 hide_index()

    df[["Unit", "Abbreviation", "Storage"]].style.hide_index()  
    
  2. 要应用于列的子集,您可以使用 subset 参数。默认情况下,第一列左对齐,其他两列使用 subset 参数居中对齐。

    set_properties(subset=["Abbreviation", "Storage"], **{'text-align': 'center'})
    

代码:

import pandas as pd
from IPython.display import HTML
df = pd.DataFrame({'Unit': ['Bit', 'Nibble','Byte/Octet', 'Kilobyte', 'Megabyte', 'Gigabyte', 'Terabyte'], 'Abbreviation': ['b', '-', 'B', 'KB', 'MB', 'GB', 'TB'], 'Storage': ['Binary digit, single 0 or 1', '4 bits', '8 bits', '1024 bytes', '1024 KB', '1024 MB', '1024 GB']})
df[["Unit", "Abbreviation", "Storage"]].style.hide_index().set_properties(subset=["Abbreviation", "Storage"], **{'text-align': 'center'})

结果:

用法:

假设您有一个 Excel 电子表格,并且您想要打印一个自定义格式的 table,它看起来比 Excel 的内置 table 模板更好.您需要做的就是在 Excel 中打开电子表格并将其导出为 csv 文件。然后 运行 下面的 Python 代码将 csv 文件转换为 Pandas df.

import pandas as pd
filepath = '/path/to/FILE.csv' # replace with an existing path to FILE.csv
df = pd.read_csv(filepath)
df

使用此 df 制作自定义格式 table。

使用 Python 3.6,我通过应用 Hagbard 建议的代码和 display(dfStyler) 来管理这个,如下所示:

import pandas as pd
df = pd.DataFrame({'Unit': ['Bit', 'Nibble','Byte/Octet', 'Kilobyte', 'Megabyte', 'Gigabyte', 'Terabyte'], 'Abbreviation': ['b', '-', 'B', 'KB', 'MB', 'GB', 'TB'], 'Storage': ['Binary digit, single 0 or 1', '4 bits', '8 bits', '1024 bytes', '1024 KB', '1024 MB', '1024 GB']})
dfStyler = df.style.set_properties(subset=["Abbreviation", "Storage"],**{'text-align': 'center'})
dfStyler = df.style.set_properties(subset=["Unit"],**{'text-align': 'left'})
dfStyler.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])

display(dfStyler.hide_index())