【发布时间】:2019-11-14 14:55:50
【问题描述】:
我正在尝试学习机器学习,我需要为工作流程的清洁阶段填写缺失值。我有 13 列,需要估算其中 8 列的值。一列称为 Dependents,我想用缺失的单词填写空白,并将包含数据的单元格更改如下:1 到 1、2 到 2、3 到 3 和 3+ 到 threePlus。
我在 Anaconda 中运行程序,数据框的名称是 train
train.columns
这给了我
Index(['Loan_ID', '性别', '已婚', '家属', '教育', 'Self_Employed'、'ApplicantIncome'、'CoapplicantIncome'、'LoanAmount'、 'Loan_Amount_Term'、'Credit_History'、'Property_Area'、'Loan_Status']、 dtype='object')
下一个
print("Dependents")
print(train['Dependents'].unique())
这给了我
家属 ['0' '1' '2' '3+' 南]
现在我尝试按所述估算值
def impute_dependent():
my_dict={'1':'one','2':'two','3':'three','3+':'threePlus'};
return train.Dependents.map(my_dict).fillna('missing')
def convert_data(dataset):
temp_data = dataset.copy()
temp_data['Dependents'] = temp_data[['Dependents']].apply(impute_dependent,axis=1)
return temp_data
这给出了错误
TypeError Traceback (most recent call last)
<ipython-input-46-ccb1a5ea7edd> in <module>()
4 return temp_data
5
----> 6 train_dataset = convert_data(train)
7 #test_dataset = convert_data(test)
<ipython-input-46-ccb1a5ea7edd> in convert_data(dataset)
1 def convert_data(dataset):
2 temp_data = dataset.copy()
----> 3 temp_data['Dependents'] =
temp_data[['Dependents']].apply(impute_dependent,axis=1)
4 return temp_data
5
D:\Anaconda2\lib\site-packages\pandas\core\frame.py in apply(self, func,
axis, broadcast, raw, reduce, result_type, args, **kwds)
6002 args=args,
6003 kwds=kwds)
-> 6004 return op.get_result()
6005
6006 def applymap(self, func):
D:\Anaconda2\lib\site-packages\pandas\core\apply.py in get_result(self)
140 return self.apply_raw()
141
--> 142 return self.apply_standard()
143
144 def apply_empty_result(self):
D:\Anaconda2\lib\site-packages\pandas\core\apply.py in apply_standard(self)
246
247 # compute the result using the series generator
--> 248 self.apply_series_generator()
249
250 # wrap results
D:\Anaconda2\lib\site-packages\pandas\core\apply.py in
apply_series_generator(self)
275 try:
276 for i, v in enumerate(series_gen):
--> 277 results[i] = self.f(v)
278 keys.append(v.name)
279 except Exception as e:
TypeError: ('impute_dependent() takes 0 positional arguments but 1 was
given', 'occurred at index 0')
我希望 one、two、three 和 threePlus 替换现有值,而缺失的值可以填补空白
【问题讨论】:
-
最好建一个dict:
my_dict={'1':'one',...},然后使用df.col.map(my_dict)。 -
我没想到所以 my_dict={'1':'one','2':'two','3','three','3+':'threePlus'}但是 nan 值呢? df.col.map(my_dict) 会变成 train.Dependants.map(my_dict)
-
我试过这个但它不起作用 def impute_dependants(cols): Dependents = cols[0] if pd.isnull(Dependents): return "missing" else my_dict={'1':'one' ,'2':'two','3','three','3+':'threePlus'} train.Dependants.map(my_dict)
-
@QuangHoang 我试过这个但它不起作用 def impute_dependants(cols): Dependents = cols[0] if pd.isnull(Dependents): return "missing" else my_dict={'1':' one','2':'two','3','three','3+':'threePlus'} train.Dependants.map(my_dict)
-
def impute_dependent(): my_dict={'1':'one','2':'two','3','three','3+':'threePlus'}; return train.Dependants.map(my_dict).fillna('missing')
标签: python-3.x pandas