如何将对象Dtype转换为int64?

问题描述

我有以下数据。

enter image description here

当我检查这些字段的DType时,它显示 object ,现在我的要求是将它们转换为 int64

#   Column        Non-Null Count  Dtype  
---  ------        --------------  -----  
 0   area_type     3 non-null      object 
 1   availability  3 non-null      object 
 2   location      3 non-null      object 
 3   size          3 non-null      object 
 4   society       3 non-null      object 

有人可以通过代码帮助我进行转换吗?我尝试使用下面的代码,但抛出了错误

dataset['area_type'] = dataset['area_type'].str.replace(',','').astype(int)

错误

ValueError: invalid literal for int() with base 10: 'Super built-up  Area'

解决方法

我已经尝试过使用 LabelEncoder ,并且对我来说很好。

from sklearn.preprocessing import LabelEncoder 
  
le = LabelEncoder() 
  
dataset['area_type']= le.fit_transform(dataset['area_type']) 
dataset['availability']= le.fit_transform(dataset['availability'])
dataset['location']= le.fit_transform(dataset['location'])
dataset['size']= le.fit_transform(dataset['size'])
dataset['society']= le.fit_transform(dataset['society'])