pandas替换一列中的汉字为数字

表格的一列“总金额”应该全部为数字,但其中少数项出现汉字,应该将汉字替换为数字,才能进行后面的计算。

先定义一个函数:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
 
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
 
    return False
 

  再引用这个函数:

df['成交金额'] = df['成交金额'].map(lambda x: np.where(is_number(x), x, 1000)) #先替换
df['成交金额'] = df['成交金额'].apply(pd.to_numeric) #类型指定为数值型
df['成交金额'] = round(df['成交金额']/100000000,2) #再计算

  

猜你喜欢

转载自www.cnblogs.com/sxinfo/p/10527498.html