Pandas数据帧列:用NUB替换字符串值时出错

2024-10-01 15:38:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含整数和'NA'值的dataframe列。下面是列的唯一值

 print(testData.LotFrontage.unique())  

 ['80' '81' '74' '78' '43' '75' 'NA' '63' '85' '70' '26' '21' '24']

我需要用整数0替换此字符串NA。我尝试了以下代码

NAReplace = {'NA': 0}

trainingData.LotFrontage = [NAReplace[item] for item in trainingData.LotFrontage ]

我得到了一个错误

    trainingData.LotFrontage = [NAReplace[item] for item in trainingData.LotFrontage ]
KeyError: '65'

这个问题的原因是什么?还有别的办法吗


Tags: 字符串代码indataframefor错误整数item
2条回答

原因是NAReplace被定义为字典,语法NAReplace[item]要求itemNAReplace的键,否则会看到KeyError

在任何情况下,列表理解在这里都不合适。只需使用fillna

testData['LotFrontage'] = testData['LotFrontage'].replace('NA', 0)

很可能您需要数字数据,在这种情况下,我建议您转换为数字:

testData['LotFrontage'] = pd.to_numeric(testData['LotFrontage'], errors='coerce').fillna(0)

参数errors='coerce'强制不可转换的值给出NaN

因为,在列表理解中,你得到字典中所有值的值

八十 81 ..

字典将试图找到那些也不是'NA'的键,因此您必须执行get

trainingData.LotFrontage = [NAReplace.get(item,item) for item in trainingData.LotFrontage ]

此外,pandasicer将:

testData['LotFrontage'] = pd.to_numeric(testData['LotFrontage'],errors='coerce').fillna(0)

另一个来自jpp的回答

但要在jpp的第一份报告中添加一些内容:

testData['LotFrontage'].replace('NA', 0,inplace=True)

相关问题 更多 >

    热门问题