我有一个汽车数据集,我想在这里替换“?”列中的值已归一化--值达到剩余数值的平均值。我使用的代码是:
mean = df["normalized-losses"].mean()
df["normalized-losses"].replace("?",mean)
但是,这会产生错误:
'???164164?158?158?192192188188??121988111811811814814814814811014513713710110110111078106106858585107????145??104104104113113150150150150129115129115?115118?93939393?142???161161161161153153???125125125137128128128122103128128122103168106106128108108194194231161161??161161??16116116111911915415415474?186??????1501041501041501048383831021021021021028989858587877477819191919191919191168168168168134134134134134134656565656519719790?1221229494949494?256???1037410374103749595959595‘:ValueError:无法将字符串转换为浮动:
有人能帮我改变一下“吗?”值到平均值。另外,这也是我第一次使用Pandas软件包,所以如果我犯了任何愚蠢的错误,请原谅我。
发布于 2018-11-29 01:52:58
使用to_numeric
将非数值值转换为NaN
值,然后使用fillna
和mean
vals = pd.to_numeric(df["normalized-losses"], errors='coerce')
df["normalized-losses"] = vals.fillna(vals.mean())
#data from jpp
print (df)
normalized-losses
0 1.0
1 2.0
2 3.0
3 3.4
4 5.0
5 6.0
6 3.4
详细信息
print (vals)
0 1.0
1 2.0
2 3.0
3 NaN
4 5.0
5 6.0
6 NaN
Name: normalized-losses, dtype: float64
print (vals.mean())
3.4
发布于 2018-11-29 01:47:05
使用replace()
,后跟fillna()
df['normalized-losses'] = df['normalized-losses'].replace('?',np.NaN)
df['normalized-losses'].fillna(df['normalized-losses'].mean())
发布于 2018-11-29 01:53:27
未定义一系列混合类型的平均值。转换为数字,然后使用replace
df = pd.DataFrame({'A': [1, 2, 3, '?', 5, 6, '??']})
mean = pd.to_numeric(df['A'], errors='coerce').mean()
df['B'] = df['A'].replace('?', mean)
print(df)
A B
0 1 1
1 2 2
2 3 3
3 ? 3.4
4 5 5
5 6 6
6 ?? ??
如果需要替换所有非数字值,则使用fillna
。
nums = pd.to_numeric(df['A'], errors='coerce')
df['B'] = nums.fillna(nums.mean())
print(df)
A B
0 1 1.0
1 2 2.0
2 3 3.0
3 ? 3.4
4 5 5.0
5 6 6.0
6 ?? 3.4
https://stackoverflow.com/questions/53535904
复制相似问题