Convert object data type to string issue in python

后端 未结 3 1913
执笔经年
执笔经年 2020-12-02 02:31

How can I convert an object dtype structure to a string dtype? The method below is not working and the column remains object after converting to a string with <

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 03:05

    object is the default container capable of holding strings, or any combination of dtypes.

    If you are using a version of pandas < '1.0.0' this is your only option. If you are using pd.__version__ >= '1.0.0' then you can use the new experimental pd.StringDtype() dtype. Being experimental, the behavior is subject to change in future versions, so use at your own risk.

    df.dtypes
    #country    object
    
    # .astype(str) and .astype('str') keep the column as object. 
    df['country'] = df['country'].astype(str)
    df.dtypes
    #country    object
    
    df['country'] = df['country'].astype(pd.StringDtype())
    df.dtypes
    #country    string
    

提交回复
热议问题