如何将对象转换为数字

我在 DataFrame 列之一中有非常不一致的数据:


col1

12.0

13,1

NaN

20.3

abc

"12,5"

200.9

我需要对这些数据进行标准化,并在数值中找到一个最大值,该最大值应小于 100。


这是我的代码:


df["col1"] = df["col1"].apply(lambda x: float(str(x).replace(',', '.')) if x.isdigit() else x)

num_temps = pd.to_numeric(df[col],errors='coerce')

temps = num_temps[num_temps<10]

print(temps.max())

例如,当x为 float时它会失败AttributeError: 'float' object has no attribute 'isdigit'。


一只萌萌小番薯
浏览 361回答 2
2回答

喵喵时光机

将值转换为stringby str(x),但是为了测试,还需要替换.并,清空值以供使用isdigit:df["col1"] = df["col1"].apply(lambda x: float(str(x).replace(',', '.')) if str(x).replace(',', '').replace('.', '').isdigit() else x)但这里有可能将值转换为字符串,然后使用Series.str.replace:num_temps = pd.to_numeric(df["col1"].astype(str).str.replace(',', '.'), errors='coerce')print (df)&nbsp; &nbsp; col10&nbsp; &nbsp;12.01&nbsp; &nbsp;13.12&nbsp; &nbsp; NaN3&nbsp; &nbsp;20.34&nbsp; &nbsp; NaN5&nbsp; &nbsp;12.56&nbsp; 200.9temps = num_temps[num_temps<100]print(temps.max())20.3选择:def f(x):&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; return float(str(x).replace(',','.'))&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; return np.nannum_temps = df["col1"].apply(f)print (num_temps)0&nbsp; &nbsp; &nbsp;12.01&nbsp; &nbsp; &nbsp;13.12&nbsp; &nbsp; &nbsp; NaN3&nbsp; &nbsp; &nbsp;20.34&nbsp; &nbsp; &nbsp; NaN5&nbsp; &nbsp; &nbsp;12.56&nbsp; &nbsp; 200.9Name: col1, dtype: float64

四季花海

这有效:df.replace(",", ".", regex=True).replace("[a-zA-Z]+", np.NaN, regex=True).dropna().max()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python