Pandas reading csv as string type

前端 未结 4 943
暖寄归人
暖寄归人 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:39

    Like Anton T said in his comment, pandas will randomly turn object types into float types using its type sniffer, even you pass dtype=object, dtype=str, or dtype=np.str.

    Since you can pass a dictionary of functions where the key is a column index and the value is a converter function, you can do something like this (e.g. for 100 columns).

    pd.read_csv('some_file.csv', converters={i: str for i in range(0, 100)})
    

    You can even pass range(0, N) for N much larger than the number of columns if you don't know how many columns you will read.

提交回复
热议问题