首页 > 解决方案 > 用中位数估算缺失值

问题描述

我想用中位数估算名为 Bare Nuclei 的数据框的一列,我得到了这个错误('必须是 str,而不是 int','发生在索引 Bare Nuclei')下面的代码表示列数据的唯一值 [ '裸核]

data['Bare Nuclei'].unique()
array(['1', '10', '2', '4', '3', '9', '7', '?', '5', '8', '6'],
      dtype=object)

然后,我尝试用中位数替换?nan然后nan用中位数估算,但出现上述错误

data['Bare Nuclei'] = data['Bare Nuclei'].replace('?',np.nan)
#data['Bare Nuclei'].fillna()
data.apply(lambda x: x.fillna(x.mean()),axis=0)

要检查数据,请访问此链接https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/

标签: python

解决方案


您得到的错误是因为存储在'Bare Nuclei'列中的值存储为字符串,但该mean()函数需要数字。您可以看到它们是您调用的结果中的字符串.unique()

替换'?'字符后,您可以使用以下命令将系列转换为数字.astype(float)

data['Bare Nuclei'] = data['Bare Nuclei'].replace('?',np.nan)
data['Bare Nuclei'] = data['Bare Nuclei'].astype(float).apply(lambda x: x.fillna(x.mean()))

推荐阅读