TypeError:参数必须是字符串或数字 [英] TypeError: argument must be a string or number
本文介绍了TypeError:参数必须是字符串或数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码:
cat_cols = ['MSZoning','Alley','LotShape','LandContour','Utilities','LotConfig','LandSlope','Neighborhood','Condition1','Condition2','BldgType','HouseStyle','RoofStyle','RoofMatl','Exterior1st','Exterior2nd','MasVnrType','ExterQual','ExterCond','Foundation','BsmtQual','BsmtCond','BsmtExposure','BsmtFinType1','BsmtFinType2','Heating','HeatingQC','CentralAir','Electrical','KitchenQual','Functional','FireplaceQu','GarageType','GarageFinish','GarageQual','GarageCond','PavedDrive','PoolQC','Fence','MiscFeature','SaleType','SaleCondition']
from sklearn.preprocessing import LabelEncoder
le=LabelEncoder()
for col in cat_cols:
if col in dataset_train.columns:
i = dataset_train.columns.get_loc(col)
dataset_train.iloc[:,i] =le.fit_transform(dataset_train.iloc[:,i])
出现错误,如belo所示w:
It gives an error as shown below:
TypeError:参数必须是字符串或数字
TypeError: argument must be a string or number
推荐答案
这是解决问题的方法
这是我编写的代码。 (ps:幸运的是我有房价预测数据集:D)
this is the code I wrote. (ps: luckily i have the house price prediction dataset with me :D")
from sklearn.preprocessing import LabelEncoder
path="....\house pricing"
filepath=os.path.join(path,"train.csv")
dataset_train=pd.read_csv(filepath)
dataset_train
cat_features=[x for x in dataset_train.columns if dataset_train[x].dtype=="object"]
le=LabelEncoder()
for col in cat_features:
if col in dataset_train.columns:
i = dataset_train.columns.get_loc(col)
dataset_train.iloc[:,i] = dataset_train.apply(lambda i:le.fit_transform(i.astype(str)), axis=0, result_type='expand')
因此,您只需要修改
dataset_train.iloc[:,i] =le.fit_transform(dataset_train.iloc[:,i])
与
dataset_train.iloc[:,i] = dataset_train.apply(lambda i:le.fit_transform(dataset_train[i].astype(str)), axis=0, result_type='expand')
上面的lamda函数将转换每列及其数据点(行
The above lamda function will convert each column and its data points(row wise axis=0) to "str" and then pass it through the "le" or LableEncoder function via the "fit_transform" to LabelEncode it.
这篇关于TypeError:参数必须是字符串或数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文