Pandas reading csv as string type

前端 未结 4 942
暖寄归人
暖寄归人 2020-11-30 03:00

I have a data frame with alpha-numeric keys which I want to save as a csv and read back later. For various reasons I need to explicitly read this key column as a string form

4条回答
  •  佛祖请我去吃肉
    2020-11-30 03:48

    Use a converter that applies to any column if you don't know the columns before hand:

    import pandas as pd
    
    class StringConverter(dict):
        def __contains__(self, item):
            return True
    
        def __getitem__(self, item):
            return str
    
        def get(self, default=None):
            return str
    
    pd.read_csv(file_or_buffer, converters=StringConverter())
    

提交回复
热议问题