现在的位置: 首页 > web前端 > 正文

python中object类型怎样转换为unit8类型

2020年07月15日 web前端 ⁄ 共 1136字 ⁄ 字号 评论关闭

  如何把python中的DataFrame中的object对象转换成我们需要的unit8类型?


  unit8类型怎么弄


  其实很简单,只要调用help(df.infer_objects)这个方法里面就可以啦。


  或者


  In[36]:


  df=df.convert_objects(convert_numeric=True)


  df.dtypes


  Out[36]:


  Dateobject


  WDint64


  Manpowerfloat64


  2ndobject


  CTRobject


  2ndUfloat64


  T1int64


  T2int64


  T3int64


  T4float64


  dtype:object


  unit8类型代码


  Forcolumn'2nd'and'CTR'wecancallthevectorised str methodstoreplacethethousandsseparatorandremovethe'%'signandthen astype toconvert:


  In[39]:


  df['2nd']=df['2nd'].str.replace(',','').astype(int)


  df['CTR']=df['CTR'].str.replace('%','').astype(np.float64)


  df.dtypes


  Out[39]:


  Dateobject


  WDint64


  Manpowerfloat64


  2ndint32


  CTRfloat64


  2ndUfloat64


  T1int64


  T2int64


  T3int64


  T4object


  dtype:object


  In[40]:


  df.head()


  Out[40]:


  DateWDManpower2ndCTR2ndUT1T2T3T4


  02013/4/66NaN26455.270.29407533454368


  12013/4/77NaN21185.890.31257659583369


  22013/4/136NaN24705.380.29354531473383


  32013/4/147NaN20336.770.37396748681458


  42013/4/206NaN26905.380.29361528541381


  Oryoucandothestringhandlingoperationsabovewithoutthecallto astype andthencall convert_objects toconverteverythinginonego.


  总之,unit8类型给大家简单的介绍了一些,希望大家多看看。

抱歉!评论已关闭.