Set max string length in pandas

后端 未结 3 1854
梦毁少年i
梦毁少年i 2020-12-18 12:19

I want my dataframe to auto-truncate strings which are longer than a certain length.

basically:

pd.set_option(\'auto_truncate_string_exceeding_this_l         


        
3条回答
  •  无人及你
    2020-12-18 12:55

    You can use read_csv converters. Lets say you want to truncate column name abc, you can pass a dictionary with function like

    def auto_truncate(val):
        return val[:255]
    df = pd.read_csv('file.csv', converters={'abc': auto_truncate}
    

    If you have columns with different lengths

    df = pd.read_csv('file.csv', converters={'abc': lambda: x: x[:255], 'xyz': lambda: x: x[:512]}
    

    Make sure column type is string. Column index can also be used instead of name in converters dict.

提交回复
热议问题