如果列名过长,DataFrame 无论如何都会以非常困惑的形式显示 options已设置。
信息:我在 Jupyter QtConsole、pandas 0.20.1 中,在启动时指定了以下相关选项:
pd.set_option('display.max_colwidth', 20)
pd.set_option('expand_frame_repr', False)
pd.set_option('display.max_rows', 25)
问题:如果需要,如何截断 DataFrame,而不是将列换行到下一行,同时保持 expand_frame_repr=False
?
这是一个例子。同样,问题不取决于列数,而是取决于列的长度。
这不会导致问题:
df = pd.DataFrame(np.random.randn(1000, 1000),
columns=['col' + str(i) for i in range(1000)])
具有长列名的相同 DataFrame 会导致我正在讨论的问题:
df = pd.DataFrame(np.random.randn(1000, 1000),
columns=['very_long_col_name_'
+ str(i) for i in range(1000)])
有什么方法可以使第二个输出与我缺少的第一个输出一致吗? (通过指定一个选项,而不是每次想查看时都使用.iloc
。)
最佳答案
使用max_columns
from string import ascii_letters
df = pd.DataFrame(np.random.randint(10, size=(5, 52)), columns=list(ascii_letters))
with pd.option_context(
'display.max_colwidth', 20,
'expand_frame_repr', False,
'display.max_rows', 25,
'display.max_columns', 5,
):
print(df.add_prefix('really_long_column_name_'))
really_long_column_name_a really_long_column_name_b ... really_long_column_name_Y really_long_column_name_Z
0 8 1 ... 1 9
1 8 5 ... 2 1
2 5 0 ... 9 9
3 6 8 ... 0 9
4 1 2 ... 7 1
[5 rows x 52 columns]
<小时/>
另一个想法......显然不完全是你想要的,但也许你可以根据你的需要改变它。
d1 = df.add_suffix('_really_long_column_name')
with pd.option_context('display.max_colwidth', 4, 'expand_frame_repr', False):
mw = pd.get_option('display.max_colwidth')
print(d1.rename(columns=lambda x: x[:mw-3] + '...' if len(x) > mw else x))
a... b... c... d... e... f... g... h... i... j... ... Q... R... S... T... U... V... W... X... Y... Z...
0 6 5 5 5 8 3 5 0 7 6 ... 9 0 6 9 6 8 4 0 6 7
1 0 5 4 7 2 5 4 3 8 7 ... 8 1 5 3 5 9 4 5 5 3
2 7 2 1 6 5 1 0 1 3 1 ... 6 7 0 9 9 5 2 8 2 2
3 1 8 7 1 4 5 5 8 8 3 ... 3 6 5 7 1 0 8 1 4 0
4 7 5 6 2 4 9 7 9 0 5 ... 6 8 1 6 3 5 4 2 3 2
关于python - Pandas 显示: truncate column display rather than wrapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45043968/