我pd.set_option("display.colheader_justify","right")用来设置列标题.但我无法找到数据选项pd.describe_option().
如何设置数据框内的数据显示每列的左对齐或右对齐?或者,是否可以为整个行数据显示定义格式模板?
Hag*_*ard 17
@Romain给出的答案很棒,但我想总结一些评论:
# Test data
df = DataFrame({'text': ['foo', 'bar'],'number': [1, 2]})
dfStyler = df.style.set_properties(**{'text-align': 'left'})
dfStyler.set_table_styles([dict(selector='th', props=[('text-align', 'left')])])
Run Code Online (Sandbox Code Playgroud)
也会对齐所有表格文本和列标题。
Rom*_*ain 12
如果要更改Jupyter Notebook中的显示,可以使用" 样式"功能.
# Test data
df = DataFrame({'text': ['foo', 'bar'],
'number': [1, 2]})
df.style.set_properties(**{'text-align': 'right'})
Run Code Online (Sandbox Code Playgroud)
小智 12
pip3 install tabulate
from tabulate import tabulate
df = pd.DataFrame ({'Text': ['abcdef', 'x'], 'Value': [12.34, 4.2]})
print(tabulate(df, showindex=False, headers=df.columns))
Text Value
------ -------
abcdef 12.34
x 4.2
Run Code Online (Sandbox Code Playgroud)
这将自动将 pandas 标题和列数据对齐到良好的视图格式。自动将 pandas 数据框列数据向左对齐。删除 pandas 数据框中索引的显示。在标题和列数据之间放置 ----。
由于使用的解决方案pandas.Styler不适用于控制台打印(至少对我来说),因此我使用pandas 1.3.3和示例数据框想出了以下代码,打印所有字符串列左对齐(无标题):
df = pd.DataFrame({'float': [0.123, 7],
'int': [3, 357676],
'str': ["hello world", "bye"],
'cat': pd.Series(["a", "bbb"], dtype="category"),
'bool': [True, False]
})
formatters = {}
for col in df.select_dtypes("object"):
len_max = df[col].str.len().max()
formatters[col] = lambda _: f"{_:<{len_max}s}"
print(df.to_string(formatters=formatters))
Run Code Online (Sandbox Code Playgroud)
float int str cat bool
0 0.123 3 hello world a True
1 7.000 357676 bye bbb False
Run Code Online (Sandbox Code Playgroud)
如果您还想左对齐标题,请添加justify='left'. 由于某种原因,对于某些列,标题现在离左侧太远,但并非对于所有列:
print(df.to_string(formatters=formatters, justify="left"))
Run Code Online (Sandbox Code Playgroud)
float int str cat bool
0 0.123 3 hello world a True
1 7.000 357676 bye bbb False
Run Code Online (Sandbox Code Playgroud)
但是,将此模式应用于其他数据类型会失败(也适用于字符串列)。我不知道为什么会发生这种情况。请注意,字符串转换是在 via 下面添加的astype,也在 f 字符串内:
formatters = {}
for col in df.columns:
len_max = df[col].astype(str).str.len().max()
formatters[col] = lambda _: f"{_!s:<{len_max}s}"
print(col, len_max)
print(df.to_string(formatters=formatters))
Run Code Online (Sandbox Code Playgroud)
float int str cat bool
0 0.123 3 hello world a True
1 7.0 357676 bye bbb False
Run Code Online (Sandbox Code Playgroud)
我没有以相同的方式证明所有列的合理性,而是需要以不同的方式证明某些列的合理性。由于在这个线程没有提及,我想提醒的存在的subset选项:
Styler.set_properties(subset=None, **kwargs)[source]
Run Code Online (Sandbox Code Playgroud)
从与 OP 相同的示例中,可以只对“文本”列进行左对齐:
df = pd.DataFrame({'text': ['foo', 'bar'],
'number': [1, 2]})
dfStyler = df.style.set_properties(subset=['text'],**{'text-align': 'left'})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25271 次 |
| 最近记录: |