Pandas reading csv as string type

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

    Update: this has been fixed: from 0.11.1 you passing str/np.str will be equivalent to using object.

    Use the object dtype:

    In [11]: pd.read_csv('a', dtype=object, index_col=0)
    Out[11]:
                          A                     B
    1A  0.35633069074776547     0.745585398803751
    1B  0.20037376323337375  0.013921830784260236
    

    or better yet, just don't specify a dtype:

    In [12]: pd.read_csv('a', index_col=0)
    Out[12]:
               A         B
    1A  0.356331  0.745585
    1B  0.200374  0.013922
    

    but bypassing the type sniffer and truly returning only strings requires a hacky use of converters:

    In [13]: pd.read_csv('a', converters={i: str for i in range(100)})
    Out[13]:
                          A                     B
    1A  0.35633069074776547     0.745585398803751
    1B  0.20037376323337375  0.013921830784260236
    

    where 100 is some number equal or greater than your total number of columns.

    It's best to avoid the str dtype, see for example here.

提交回复
热议问题