pandas display: truncate column display rather than wrapping

后端 未结 3 1140
醉酒成梦
醉酒成梦 2021-01-19 03:43

With lengthy column names, DataFrames will display in a very messy form seemingly no matter what options are set.

Info: I\'m in Jupyter QtConsole, pandas 0.20.1, wit

3条回答
  •  旧时难觅i
    2021-01-19 04:25

    Use 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]
    

    Another idea... Obviously not exactly what you want, but maybe you can twist it to your needs.

    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 
    

提交回复
热议问题